Skip to content

Commit

Permalink
Merge pull request neetcode-gh#976 from Scorpiussmith13/main
Browse files Browse the repository at this point in the history
(Updated) 152-Maximum-Product-Subarray.cpp
  • Loading branch information
Ahmad-A0 authored Aug 31, 2022
2 parents 542cfbb + ee279ee commit e18caae
Showing 1 changed file with 11 additions and 22 deletions.
33 changes: 11 additions & 22 deletions cpp/152-Maximum-Product-Subarray.cpp
Original file line number Diff line number Diff line change
@@ -1,30 +1,19 @@
/*
Given int array, find contiguous subarray w/ max product, return product
Ex. nums = [2,3,-2,4] -> output = 6, [2,3] has max product at 6
Think wrt combo chains, if +'ve ints good, but if 0's bad, if -'ve depends
0's force reset, -'ve could sway the best ans, therefore track currMax & currMin
Time: O(n)
Space: O(1)
*/

class Solution {
public:
int maxProduct(vector<int>& nums) {
int currMax = nums[0];
int currMin = nums[0];
int result = nums[0];
int res = nums[0];
int curMin = 1, curMax = 1;

for (int i = 1; i < nums.size(); i++) {
int temp = currMax;

currMax = max(max(currMax * nums[i], currMin * nums[i]), nums[i]);
currMin = min(min(currMin * nums[i], temp * nums[i]), nums[i]);

result = max(result, currMax);
for(int i = 0; i < nums.size(); i++)
{
int n = nums[i];

int tmp = curMax * n;
curMax = max(max(n * curMax, n * curMin), n);
curMin = min(min(tmp, n * curMin), n);
res = max(res, curMax);
}

return result;
return res;
}
};

0 comments on commit e18caae

Please sign in to comment.