How to find a sequential sub array which has the biggest sum [reviewed]

Problem

Given a number array, including positive and negative numbers, the question is to find a sequential sub array which has the biggest sum and the time complexity is $O(n)$,

For example, [1,-2,3,10,-4,7,2,-5] is an array, and the sub array [3, 10, -4, 7, 2] has the biggest sum which is 18.



This question is quite similar to "Finding the sequential sub array totaling the given number".
If you did not read this. I recommend you to do so before continue.

Difference is that there is no fixed length, N for the sub array and no given sum, S.

However, we can adopt the same strategy as in "Finding the sequential sub array totaling the given number" with the minor modification.

Take a look at the following illustration.

Figure 1. Initial iteration
As you can see in Figure 1. we use two pointers, start and end to remember the latest max sub array.
Max is to remember the sum of the sub array,

We also keep track of the sum of all numbers up to the current position, i as well.

From this time on, we keep scanning the next element in i th position and check if the current sum up to i is larger than the last max value and make the following decisions:

Case 1) $\text{current sum }\gt \text{ max}$ : in this case we move the "end" pointer to i th position and replace the "Max" with the current sum.

Case 2) $\text{current sum }\lt \text{ max}$: we simply ignore the i th position element. No update to "end" and "Max". We just move on. However, we still need to update "Current sum".

Case 3) $\text{current sum }\le \text{ 0}$: This is an edge case. If current sum up to i become zero or negative value. We know that adding any elements up to i th position would not any value to the final sub array. In this case, we simply move both "start" and "end" to i+1 th position in the next iteration.

Don't forget to reset the current sum so that we start suming up numbers from i+1 th position as show in Figure 2, 3.
Figure 2: Special Case when current sum $\le$ 0

Figure 3: After resetting "Start" to i+1
Overall running time is still $O(N)$.

Here is the complete algorithm.



Practice statistics

15:30 : to hand-wrote the code on the paper
10:06.96: to code in the IDE.
04:11.44: to write the test case and validate the code


UPDATE(2019-07-26): solved the problem again.  Did not think of the case to move Start pointer.

Here is a python version of solution:


Practice statistics:

17:00 to write up the answer
Had to fix the logic error afterward. This should not happen.

Comments

Popular posts from this blog

Planting flowers with no adjacent flower plots

Stock price processing problem