Maximum Product Subarray

Medium

Topics
ArrayDynamic Programming

Given an integer array nums, find a contiguous non-empty subarray that has the largest product, and return the product.

Example 1

2031-2243product = 6
The braced run has the largest product, 6. Unlike the sum version a negative running value is valuable — one more negative flips it to a large positive — so the scan has to carry the running minimum alongside the running maximum, and swap them at each negative element.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [2,3,-2,4]
Output: 6

Example 2

-2001-12product = 0
Input:  nums = [-2,0,-1]
Output: 0

Constraints

  • 1 <= nums.length <= 2*10^4
  • -10 <= nums[i] <= 10
  • Answer fits in a 32-bit integer.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Products differ from sums because two negatives make a positive, so the smallest (most negative) running product can suddenly become the largest.

Track both the running maximum and running minimum ending at each index; on a negative number, swap them, because multiplying flips which is largest.

Approach

  1. Keep mx, mn (max/min product ending here) and global res.
  2. If the current number is negative, swap mx and mn.
  3. Update mx = max(x, mx*x), mn = min(x, mn*x).
  4. Update res = max(res, mx).

Walkthrough

nums = [2, 3, -2, 4]
x=2  mx=2 mn=2 res=2
x=3  mx=6 mn=3 res=6
x=-2 swap -> mx=3 mn=6; mx=max(-2,-6)=-2 mn=min(-2,-12)=-12 res=6
x=4  mx=max(4,-8)=4 res=6  -> answer 6

Complexity

  • Time — O(n): single pass.
  • Space — O(1): three scalars.

Common Pitfalls

  • You must track the minimum too — a lone max would miss the negative×negative flip.

Full Solution — all languages

class Solution:
    def maxProduct(self, nums):
        res = curMax = curMin = nums[0]
        # range, not nums[1:], which would copy n-1 elements and break the O(1) claim
        for i in range(1, len(nums)):
            x = nums[i]
            if x < 0:
                curMax, curMin = curMin, curMax
            curMax = max(x, curMax * x)
            curMin = min(x, curMin * x)
            res = max(res, curMax)
        return res
SensAI
Beta
Tap the mic to stop voice mode