152. Maximum Product Subarray
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- 1-D Dynamic Programming
- Time
- O(N)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven an integer array, find the contiguous subarray (containing at least one element) whose elements multiply together to produce the largest possible product, and return that product.
Approach
- Track both
curMaxandcurMinat each position, because multiplying by a negative number flips which extreme is which. - At each element, the new running max is the largest of: extending the previous max, extending the previous min (useful when the current element is negative), or starting fresh with just the current element.
- The running min is updated symmetrically so future negative elements can turn a large negative into a large positive.
- The global answer is updated after each step from
curMax.
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxProduct(vector<int>& nums) {
// Seed all trackers with the first element.
int curMax = nums[0];
int curMin = nums[0];
int result = nums[0];
for (int i = 1; i < (int)nums.size(); ++i) {
int n = nums[i];
// Multiplying by n may swap which of curMax/curMin is larger,
// so compute both candidates before updating either.
int candidates[3] = { n, curMax * n, curMin * n };
curMax = *max_element(candidates, candidates + 3);
curMin = *min_element(candidates, candidates + 3);
result = max(result, curMax);
}
return result;
}
};
Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
int maxProduct(vector<int>& nums) {
int curMin=nums[0];
int curMax=nums[0];
int globalMax=nums[0];
for(int i=1; i<nums.size(); ++i){
int n=nums[i];
if(n>=0){
curMin=std::min(curMin*n, n);
curMax=std::max(curMax*n, n);
}
else{ // n<0
int tmpMin=curMin;
curMin=std::min(curMax*n, n);
curMax=std::max(tmpMin*n, n);
}
globalMax=std::max(globalMax, curMax);
}
return globalMax;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) Time O(N) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.