← DSA
MEDIUM

Maximum Product Subarray

PracticeNeetCode ↗LeetCode ↗

Given an integer array nums, return the largest product achievable by any contiguous subarray.

Example

Input nums = [2,3,-2,4]
Output 6

Key Pointers

Step-by-Step Analysis

  1. Initialize result, cur_max, and cur_min all to nums[0].
  2. For each following number n, compute the three candidates: n itself, n × cur_max, and n × cur_min.
  3. Set cur_max to the largest of the three candidates and cur_min to the smallest.
  4. Update result to the larger of itself and cur_max; return result once the array is exhausted.

Complexity

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

Code

def maxProduct(nums: list[int]) -> int:
    result = nums[0]
    cur_max, cur_min = nums[0], nums[0]

    for n in nums[1:]:
        candidates = (n, n * cur_max, n * cur_min)
        cur_max, cur_min = max(candidates), min(candidates)
        result = max(result, cur_max)

    return result

Code Explanation

How the solution above works, piece by piece.

  1. For each position, track the largest and the smallest product of a subarray ending there.
  2. The smallest matters because a negative number flips signs: a very negative product times a negative becomes very positive.
  3. The new max/min come from three candidates: start fresh at n, extend the previous max, or extend the previous min.
  4. result keeps the best max seen anywhere.
  5. One pass, O(1) space.

Visual Walkthrough

Running it on nums = [2, 3, -2, 4]:

trace2031-2243i=0max 2, min 2, result 223-24i=1max 6, min 3, result 623-24i=2max -2, min -12, result 623-24i=3max 4, min -48, result 6
At −2 the best product so far (6) turns into −12 as the new minimum; it would become useful if another negative number came later. The answer is 2 × 3 = 6.
current number

Video Explanation

NeetCode — Dynamic Programming, LeetCode 152