I’m currently reading Jon Bentley’s “Programming Pearls”, in which there is a question I just can’t seem to be able to answer. Here it is:
In the maximum subarray problem we are given an nxn array of reals, and we must find the maximum sum contained in any rectangular subarray.
In the chapter, it lists an algorithm for finding the max of an array:
maxsofar = 0
maxendinghere = 0
for i = [0, n) // n) = n-1
/*ivariant: maxendinghere and maxsofar are accurate for x[0…i-1] */
maxendinghere = mac(maxendinghere + x[i], 0)
maxsofar = mac(maxsofar, maxendinghere)
I’m considering whether you can just say something along the lines of
for all columns
for all rows
the algorithm shown above
But I’m not sure that would work. Any Ideas?
first of all, u have to understand 1d array version: maximum continuous sum of a 1d array.
to solve the 1d array version, the algorithm is straightforward and u have given out above.
this is O(n). then we can expend to the 2d version. for 2d version, u can convert it to 1d version and still use the above algorithm, but how? just sum up the values in one column, and treat the sum as the new 1d array. example:
the matrix is 2*2 as follow:
after sum up, u can get
got it? all u need to do is enumerate all possible ways to calculate the column sum starting from the ith row to jth row. and then apply the above key algorithm. pseudocode:
total complexicity is O(n^3)