↻one more pass.
Dynamic programming · Medium

Maximum Product Subarray: the idea to remember.

Find the largest product of any nonempty contiguous integer subarray.

Solve on LeetCode ↗

The core insight

Keep both the largest and smallest products ending here because multiplying by a negative reverses their roles.

Why it works

Every product ending here is the current value alone or the current value times one of the previous product extremes.

The mistake to avoid

Do not overwrite the old maximum before computing the new minimum; zeros naturally restart candidates. Products are assumed to fit the input contract.

Time: O(n)Space: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int maxProduct(int[] nums) {
    int high = nums[0], low = nums[0], best = nums[0];
    for (int i = 1; i < nums.length; i++) {
        int n = nums[i], oldHigh = high;
        high = Math.max(n, Math.max(high * n, low * n));
        low = Math.min(n, Math.min(oldHigh * n, low * n));
        best = Math.max(best, high);
    }
    return best;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.