The input to this problem is an array A[1...n]
of real numbers. Your need to find out what the highest value is that can be obtained by summing up all numbers of a contiguous subsequence A[i],A[i+1],...A[j]
of A
. If A
does not contain negative numbers, the problem is trivial and can be solved by summing up all the elements of A
. It becomes more tricky when A
contains a mix of positive and negative numbers though.
For instance, for A = [-2,11,-4,13,-5,-3]
, the solution is 20
(11-4+13=20). For A = [-2,1,-3,4,-1,2,1,-5,4]
, the solution is 6
(4-1+2+1=6). The sum of the numbers of an empty subsequence is 0
.
There exists a brute force solution that solves this problem in O(n^3), but it is also possible to solve the problem in linear time.
- Design an algorithm that solves the problem described above in linear time. Present your algorithm in pseudo-code.
- Briefly explain how and why your algorithm works.
- Give a brief explanation of why your algorithm indeed runs in linear time.