Maximum Product Subarray

Medium1-D dynamic programming

Given an array of integers nums, find the non-empty run of neighbouring values whose product is largest, and return that product.

Examples

Example 1
Input:  nums = [3, -1, 4, 2]
Output: 8

4 × 2. Any run that includes -1 is negative.

Example 2
Input:  nums = [-2, 3, -4]
Output: 24

The whole array: its two negatives cancel out.

Constraints

  • 1 ≤ nums.length ≤ 2 × 10⁴
  • -10 ≤ nums[i] ≤ 10
  • The product of any run fits in a 32-bit integer.

Stuck?

Hint 1

A negative number turns the smallest product so far into the largest. So the best product ending here comes from the best or the worst product ending one step earlier.

Hint 2

Keep both the largest and the smallest product of a run ending at the current value; a zero restarts both. Track the best largest you have seen.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur