Problem Statement
Given a sequence of N positive or negative numbers, find a contiguous sub-array whose numbers have the largest sum.
Example: The Max 1D range sum of [−2, 1, −3, 4, −1, 2, 1, −5, 4] is 6 resulting from the [−2, 1, −3, 4, −1, 2, 1, −5, 4] sub-array.
General Idea
This problem can be solved using Kadane’s algorithm. The gist of it is to
- Keep track of the current
result
and add each number in the sequence tosum
- If
sum > result
, letresult = sum
- After going through all the numbers,
result
will contain the sum of the sub-array whose numbers have the largest sum.
The above solution can also be added upon to detect the start and the end of the sub-array.
Complexity: \(O(n)\)
Code
C++11 code Below