Maximum Product Subarray - Problem

Given an integer array nums, find the contiguous subarray (containing at least one element) that has the largest product, and return that product.

This is a twist on the classic Maximum Subarray problem! Unlike sum where we only worry about negative numbers, with products we need to consider both negative numbers (which can flip signs) and zeros (which reset everything).

Key Challenge: A negative number can turn a small product into a large one if multiplied by another negative number!

Example: In array [2,3,-2,4], the maximum product subarray is [2,3] with product 6, not the entire array which gives -48.

Input & Output

example_1.py โ€” Basic Case
$ Input: [2,3,-2,4]
โ€บ Output: 6
๐Ÿ’ก Note: The subarray [2,3] has the largest product 6. Even though the entire array multiplies to -48, we stop at [2,3] to get the maximum.
example_2.py โ€” Single Element
$ Input: [-2]
โ€บ Output: -2
๐Ÿ’ก Note: With only one element, the maximum product subarray is the element itself, which is -2.
example_3.py โ€” Zero in Array
$ Input: [-2,0,-1]
โ€บ Output: 0
๐Ÿ’ก Note: The result is 0 because we can choose the subarray [0] which gives product 0, better than any negative products from [-2] or [-1].

Constraints

  • 1 โ‰ค nums.length โ‰ค 2 ร— 104
  • -10 โ‰ค nums[i] โ‰ค 10
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer

Visualization

Tap to expand
Portfolio Growth TrackingDay:+100%+50%-50%+300%Best Streak:2x3x1.5x6xWorst Streak:2x1.5x0.75x0.75xMaximum Growth: 3x
Understanding the Visualization
1
Track Best and Worst Streaks
Keep track of your current best and worst performing periods
2
Handle Negative Days
On negative days, your worst streak might become your best tomorrow
3
Reset on Zero
Market crashes (zeros) reset everything - start fresh
4
Update Maximum
Always remember your historical best performance
Key Takeaway
๐ŸŽฏ Key Insight: By tracking both best and worst streaks simultaneously, we can handle the sign-flipping nature of negative numbers and always capture the optimal subarray product.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28 Apple 25
52.3K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen