DSA Tracker

Medium

Maximum Product Subarray

A medium Arrays problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Arrays
Sheets
2
Core for
25 roles
Platform
LeetCode

The problem

Given an integer array, find the contiguous subarray that has the largest product of its elements.

Example 1

Input
nums = [2,3,-2,4]
Output
6
Why
The contiguous subarray [2,3] gives the largest product of 6.

Example 2

Input
nums = [-2,0,-1]
Output
0
Why
The largest product attainable is 0, since picking either negative number alone yields less.

Example 3

Input
nums = [-2,3,-4]
Output
24
Why
The product of the entire array is (-2) * 3 * (-4) = 24 due to the double negative.

Constraints

  • 1 <= nums.length <= 2*10^4
  • -10 <= nums[i] <= 10

How to think about it

Updated 2026-09-09

Multiplication by a negative number flips signs: a tiny negative product suddenly becomes a huge positive product when struck by another negative. Because an extreme negative is only one step away from becoming the maximum, tracking both the running maximum and the running minimum at every step is necessary to capture sign flips.

Approaches, worst first

  1. Exhaustive subarray product

    time O(n^2) · space O(1)

    Evaluate every contiguous range (i, j) by multiplying elements in nested loops and recording the highest product seen. Solves the task directly, but runs in quadratic time and risks numerical overflow on larger subarrays.

  2. Dual max-min dynamic trackingWrite this one

    time O(n) · space O(1)

    Maintain currentMax and currentMin seeded with nums[0]. For each subsequent number, if negative, swap the two accumulators. Then update both by taking max and min between the number itself and its product with the previous bounds. Updates the global answer in one pass.

Where people lose marks · 3
  • Updating currentMax and then using that newly updated value to compute currentMin in the same iteration without preserving the old max.
  • Overlooking the reset effect of 0, which zeroes out the running product and forces subsequent subarrays to start fresh from the next element.
  • Initializing max product to 0 or 1 instead of nums[0], which fails when the array contains only a single negative number like [-2].

Full solution

Dual max-min dynamic tracking: keep the running maximum AND minimum product ending at each index, swapping them when the current number is negative. One pass, constant space, and it is the only linear approach that survives sign flips and zeros.

Python
from typing import List


def max_product(nums: List[int]) -> int:
    best = cur_max = cur_min = nums[0]
    for x in nums[1:]:
        if x < 0:
            cur_max, cur_min = cur_min, cur_max  # a negative flips which extreme is which
        cur_max = max(x, cur_max * x)
        cur_min = min(x, cur_min * x)
        best = max(best, cur_max)
    return best
JavaScript
function maxProduct(nums) {
  let best = nums[0];
  let curMax = nums[0];
  let curMin = nums[0];
  for (let i = 1; i < nums.length; i++) {
    const x = nums[i];
    if (x < 0) [curMax, curMin] = [curMin, curMax]; // a negative flips which extreme is which
    curMax = Math.max(x, curMax * x);
    curMin = Math.min(x, curMin * x);
    best = Math.max(best, curMax);
  }
  return best;
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

What each operation costs

OperationTime
look up element by indexO(1)
insert or delete at the startO(n)
search an unsorted collection for a valueO(n)
What usually goes wrong with Arrays
  • Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
  • Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
  • Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.

Which roles need this problem

Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Arrays problems

Problem set and role mapping as of .