Kadane's algorithm
Largest sum of any contiguous subarray, including arrays with negative numbers.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
At each element decide: extend the running subarray, or start fresh here. If the running sum has gone negative it can only hurt, so drop it.
Code
int maxSubArray(const vector<int>& a) {
int cur = a[0], best = a[0];
for (int i = 1; i < (int)a.size(); i++) {
cur = max(a[i], cur + a[i]);
best = max(best, cur);
}
return best;
}def max_sub_array(a: list[int]) -> int:
cur = best = a[0]
for x in a[1:]:
cur = max(x, cur + x)
best = max(best, cur)
return bestpublic static int MaxSubArray(int[] a) {
int cur = a[0], best = a[0];
for (int i = 1; i < a.Length; i++) {
cur = Math.Max(a[i], cur + a[i]);
best = Math.Max(best, cur);
}
return best;
}Tips
- cur is the best sum ending exactly at this index. best is the best seen anywhere.
- It is the simplest dynamic programming problem: each answer depends only on the previous one.
In the .NET library
No built-in. Use long instead of int if the values can be large enough for the running sum to overflow.