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 INPUT Integer Array nums[] 2 i=0 3 i=1 -2 i=2 4 i=3 Input Values: nums = [2, 3, -2, 4] Challenge: Negative numbers can flip min to max when multiplied by another negative! ALGORITHM STEPS 1 Initialize DP Variables maxProd=2, minProd=2, result=2 2 Track Both Max and Min Keep min for negative flips 3 Update at Each Index Compare: num, max*num, min*num 4 Track Global Maximum result = max(result, maxProd) DP Trace Table i num maxP minP res 0 2 2 2 2 1 3 6 3 6 2 -2 -2 -12 6 3 4 4 -48 6 Max product found at i=1: 2*3=6 FINAL RESULT Maximum Product Subarray Found: 2 3 -2 4 Subarray [2,3] Product Calculation: 2 x 3 = 6 OUTPUT 6 OK - Maximum product is 6 Key Insight: Unlike maximum sum subarray, we must track BOTH maximum AND minimum products at each position. A negative number can turn a minimum product into maximum when multiplied by another negative. Time Complexity: O(n) | Space Complexity: O(1) - Single pass with constant extra space. TutorialsPoint - Maximum Product Subarray | Dynamic Programming Approach
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