Maximum Product Subarray - Problem

Given an integer array nums, find a subarray that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

Note: The product of an array with a single element is the value of that element.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,-2,4]
Output: 6
💡 Note: The subarray [2,3] has the largest product 6.
Example 2 — All Negative
$ Input: nums = [-2,0,-1]
Output: 0
💡 Note: The result cannot be 2, because [-2,-1] is not a subarray.
Example 3 — Single Element
$ Input: nums = [-2]
Output: -2
💡 Note: Single element subarray has product -2.

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
Maximum Product Subarray: Find Best Contiguous Subarray23-24Input: [2, 3, -2, 4]Best SubarraySubarray [2, 3] has product: 2 × 3 = 6Output: 6
Understanding the Visualization
1
Input Array
Given array with positive and negative numbers
2
Find Subarrays
Consider all contiguous subarrays
3
Maximum Product
Return the largest product found
Key Takeaway
🎯 Key Insight: Negative numbers can flip small products into large ones, so we must track both maximum and minimum products at each position
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
67.5K Views
High Frequency
~25 min Avg. Time
1.9K 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