Skip to content

Maximum Product Subarray

MediumDynamic Programming
Decode it first. Clues, constraints, pattern and plan before any code.

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

nums = [2, 3, -2, 4]   →  6    ([2, 3])
nums = [-2, 0, -1]     →  0    ([0])
nums = [-2, 3, -4]     →  24   (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.