Maximum Product Subarray

Max product of any contiguous subarray — track current max AND current min (negatives flip).

Medium
Time O(n) Space O(1)
LeetCode
3 min read
dp array

Problem#

Return the largest product of any contiguous non-empty subarray.

Examples#

  • [2,3,-2,4]6 ([2,3])
  • [-2,0,-1]0

Constraints#

  • 1 <= n <= 2 * 10^4.

Approach#

Track two running values: curMax and curMin ending at the current index. On a negative, they swap roles. Update best from curMax.

Solution#

Maximum Product Subarray
class Solution {
public:
int maxProduct(vector<int>& nums) {
int curMax = nums[0], curMin = nums[0], best = nums[0];
for (int i = 1; i < (int)nums.size(); ++i) {
int x = nums[i];
if (x < 0) swap(curMax, curMin);
curMax = max(x, curMax * x);
curMin = min(x, curMin * x);
best = max(best, curMax);
}
return best;
}
};

Editorial#

Negatives invalidate the “running max only” idea (a big negative × small negative may produce the new max). Tracking both extremes covers all cases: swapping on a negative repositions them for the multiplication.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.