UVa 108 Maximum Sum
Given an array with size \(N \times N (N \le 100)\), find the maximum value of its subarray.
Link: Problem on UVa
First thought is to brute force - find all possible subarrays then the time complexity will be \(O(N^6)\). TLE for sure.
Then comes up with an algorithm that takes \(O(N^4)\), which is enough to AC.
However, it can be \(O(N^3)\), see solution 2.
We build a
sum array which is the sum of the numbers in rectangle area with the top-left of the array and bottom-right node \(i, j)\).
Then as we can see at the graph below, it is obvious that
A &= (A+B+C+D)\\ &-(B+D)\\ &-(C+D)\\ &+D
Therefore we have
A = sum[k][l] - sum[i-1][l] - sum[j-1][k] + sum[i-1][j-1]. Go through every subarray to find the maximum.
There is a trick that store the array starts with
index 1 and initialize
0. So you don’t need to do boundary check. Stuck at first, could not figure out why and then found that I used
< instead of
<= in the
In one dimension, if we want to find the maximum sum of successive elements, we have equation: $$ d[k] = max(d[k-1]+d[k], d[k])$$ There is a small improvement. By using greedy, we know if the sum is less than 0, there is no point to “add” it, we can just discard it.
After we know how to compute in one dimension, it is easy to do it in two dimension.
i = the starting line
j = the ending line, where i <= j
k = the number of columns
We can compress all lines between
j into a 1D array. In other words, add each number in the same column together and put it in the 1D array. Hence, we have an array with
j lines in it.
Now, it is just the problem we have already seen. Find the maximum sum of successive elements in the 1D array. That is the sum of the whole rectangle in the original 2D array.