Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square with largest sum in the matrix

Tags:

algorithm

I've got quite typical problem, I think. I know there were similar topics here but understand that I'm a beginner and do not distinguish different versions of this problem. Sometimes little difference in text and the algorithm can be completely different.. So the problem is:

For a given 2<=a,b<=1000 and 1<=c<=Min(a,b) find in matrix a x b square c x c 
with the largest sum of elements. The elements in matrix are from -1000 to 1000.

I can write an algorithm that runs the entire matrix and on every point(x,y) it counts sum for a square (x,y), (x+c,y), (x,y+c), (x+c,y+c). Then I chose the largest sum. With these constraints I think it could be quite fast, but is there any faster algorithm? I'm not good at counting algorithm complexity but it seems to be O(a*b*c*c). And if I'm not wrong in the worst case it may not stop..

like image 276
xan Avatar asked Jan 17 '23 21:01

xan


1 Answers

I believe the right way to approach this is to do an integral transform first: for each element (i,j) of the original matrix M, compute integral transform matrix I(i,j) = sum[0..i, 0..j](M). By running sums in both the rows and columns directions, you can do this in O(a*b) time.

Once you have the integral transform, you can compute the sum of any sub-block in constant time as:

sum[i0..i1, j0..j1](M) = I(i1,j1) - I(i0 - 1, j1) - I(i1, j0 - 1) + I(i0 - 1, j0 - 1)

so you can compute and compare each c x c square sum in constant time, for a total of O(a*b).

like image 57
comingstorm Avatar answered Jan 24 '23 19:01

comingstorm