Skip to problem
←

Maximum Product Subarray

Medium 0 attempts

Given an integer array nums, return the maximum product of a nonempty contiguous subarray. You may choose a single element, but cannot skip elements within the chosen range.

The answer may be negative or zero. For [-2], return -2; choosing no elements is not allowed. For [-2,0,-1], return 0: the negative values cannot be combined while skipping the zero.

Function contract

Implement maxProduct(nums). Receive a nonempty integer array. Every contiguous subarray product fits a signed 32-bit integer.

Output: Return the largest product of any nonempty contiguous subarray, not its indices or elements.

Example 1

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

Example 2

Input
nums = [-2,0,-1]
Output
0
Constraints
  • 1 <= nums.length <= 2 * 10^4
  • -10 <= nums[i] <= 10
  • The product of any subarray fits in a signed 32-bit integer.

Track Min and Max

Maintain the smallest and largest products of subarrays ending at the current position. For each value, either start a new subarray or extend a previous one. A negative value can turn the previous minimum into the new maximum, so keep both. Save the previous maximum before updating either state. A zero naturally resets both ending products to zero; the next position may start fresh.

javascript
function maxProduct(nums) {
  let max = nums[0], curMax = nums[0], curMin = nums[0];
  for (let i = 1; i < nums.length; i++) {
    const temp = curMax;
    curMax = Math.max(nums[i], nums[i] * curMax, nums[i] * curMin);
    curMin = Math.min(nums[i], nums[i] * temp, nums[i] * curMin);
    max = Math.max(max, curMax);
  }
  return max;
}

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript