Analysis: During interviews, many candidates can solve it by enumerating all of sub-arrays and calculate their sum. An array with n elements has n(n+1)/2 sub-arrays. It costs O(n2) time at least to calculate their sum. Usually the intuitive and forceful solution is not the most optimized one. Interviewers will tell us that there are better solutions.
Solution 1: Analyze arrays number by number:We try to accumulate every number in the example array from first to end. We initialize sum as 0. At our first step, add the first number 1, and sum is 1. And then if we add the second number -2, sum becomes -1. At the third step, we add the third number 3. We can notice that sum is less than 0, so the new sum will be 2 and it is less than the third number 3 itself if we add it with a negative sum. Therefore, the accumulated sum can be discarded.
We continue accumulating from the third number with sum 3. When we add it with the fourth number 10, sum becomes 13, and it decreases to 9 when we add it with the fifth number -4. We can notice that the sum with -4 is less than the previous sum since -4 is a negative number. Therefore, we should store the previous sum 13, since it might be the max sum of sub-arrays. At the sixth step, we add the sixth number 7 and sum is 16. Now sum is greater than the previous max sum of sub-arrays, we need to update it to 16. It is same when we add the seventh number 2. The max sum of sub-arrays is updated to 18. Lastly we add -5 and sum becomes 13. Since it is less than the previous max sum of sub-arrays, it final max sum of sub-array is 18, and the sub-array is {3, 10, -4, 7, 2} accordingly. We can summarize the whole process with the Table 1:
|
Step
|
Operation
|
Accumulated sum of sub-arrays
|
Maximum sum
|
|
1
|
Add 1
|
1
|
1
|
|
2
|
Add -2
|
-1
|
1
|
|
3
|
Discard previous sum -1, add 3
|
3
|
3
|
|
4
|
Add 10
|
13
|
13
|
|
5
|
Add -4
|
9
|
13
|
|
6
|
Add 7
|
16
|
16
|
|
7
|
Add 2
|
18
|
18
|
|
8
|
Add -5
|
13
|
18
|
Table 1: The process to calculate the maximum sum of all sub-arrays in the array {1, -2, 3, 10, -4, 7, 2, -5}
After we get clear ideas of this solution, we are ready to develop some code. The following is the sample code:
to be continued.....