Skip to content
Decoder

Maximum Product Subarray

Medium

Problem

Given an integer array nums, find the contiguous, non-empty subarray whose elements have the largest product, and return that product.

Example 1

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

Example 2

Input
nums = [-2, 0, -1]
Output
0
Why
[0]

Example 3

Input
nums = [-2, 3, -4]
Output
24
Why
the whole array: two negatives cancel

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.