Kadane's algorithm

Largest sum of any contiguous subarray, including arrays with negative numbers.

Time O(n)Space O(1)Code C++, Python and C#
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 best
public 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

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.