Maximum product subarray

Largest product of a contiguous run of numbers. A negative value can turn the smallest product into the largest.

Time O(n)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Unlike a sum, a product can flip sign. So track both the best (most positive) and worst (most negative) product ending at each index. A negative number swaps their roles, because multiplying the most negative value by another negative gives the new most positive one.

Code

public static int MaxProduct(int[] a) {
    int maxEnd = a[0], minEnd = a[0], best = a[0];
    for (int i = 1; i < a.Length; i++) {
        if (a[i] < 0) (maxEnd, minEnd) = (minEnd, maxEnd);
        maxEnd = Math.Max(a[i], maxEnd * a[i]);
        minEnd = Math.Min(a[i], minEnd * a[i]);
        best = Math.Max(best, maxEnd);
    }
    return best;
}

Tips

In the .NET library

Forgetting the running minimum is the classic bug: code that tracks only the maximum misses cases where two negatives multiply into a new best, like 3, -2 after -4 giving a bigger product than either alone.