InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

Maximum Product Subarray

medium Original ↗
Solving tips
  • Unlike Kadane's sum, a product can flip sign, so carry BOTH the max and min product ending at each index.
  • cur_max = max(x, x*prev_max, x*prev_min); cur_min = min of the same three - a negative x swaps which extreme is best.
  • Snapshot the old cur_min before overwriting cur_max (or do the negative-swap first), or you corrupt the update.
  • Seed best = cur_max = cur_min = nums[0], not 0 (fails on [-3]); zeros reset via the standalone x candidate. O(n) time, O(1) space.

Problem

Given an integer array nums, find the contiguous non-empty subarray with the largest product of its elements, and return that product. The array may contain negative numbers and zeros. The answer is guaranteed to fit in a 32-bit integer.

Examples

  • nums = [2,3,-2,4]6 — the subarray [2,3] gives 6; extending past -2 would flip the sign.
  • nums = [-2,0,-1]0 — the best non-empty product is 0 (any window with a negative alone is worse).
  • nums = [-2,3,-4]24 — the whole array: (-2)·3·(-4) = 24; two negatives make a positive.

Constraints

  • 1 <= nums.length <= 2·10⁴
  • -10 <= nums[i] <= 10
  • Every prefix/suffix product fits in a 32-bit integer.

Think about it first

Hint 1 For a sum subarray (Kadane), you only track the best running sum. Products are trickier: a large negative running product can become the largest positive the moment you multiply by another negative. So one running value isn't enough.
Hint 2 Track two things ending at each index: the maximum product and the minimum product of a subarray ending there. A new negative number swaps their roles.
Hint 3 cur_max = max(x, x·prev_max, x·prev_min) and cur_min = min(x, x·prev_max, x·prev_min). A zero resets both (starting fresh at x handles that). Track the global best of all cur_max.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.