Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0e874ed

Browse files
Merge pull request #1 from Scorpiussmith13/Scorpiussmith13-patch-1
Updated 152-Maximum-Product-Subarray.cpp
2 parents 345cdbd + daf8bfe commit 0e874ed

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

cpp/152-Maximum-Product-Subarray.cpp

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,25 @@
1212
class Solution {
1313
public:
1414
int maxProduct(vector<int>& nums) {
15-
int currMax = nums[0];
16-
int currMin = nums[0];
17-
int result = nums[0];
15+
16+
int currMax = nums[0],currMin=nums[0],ans=nums[0]; //initializing with 1 causes bugs since line 19 stores max between ans and currMAx; Example: arr ={-2,0,-1} At the 0th index if ans = 1 then max(currMax,ans) = max(-2,1) is 1 which is wrong.
17+
1818

19-
for (int i = 1; i < nums.size(); i++) {
20-
int temp = currMax;
19+
for(int i = 1; i<nums.size();i++)
20+
21+
{
22+
int temp = currMax; // since currMax will change value in this iteration. Imp to store the previous value
23+
24+
if(nums[i] == 0) currMax = currMin = 1;
25+
26+
currMax = max(max(currMax*nums[i],currMin*nums[i]),nums[i]); //curr Max caclculates the maximum product achived right now
27+
28+
currMin = min(min(currMin*nums[i],temp*nums[i]),nums[i]);// curr Min is also imp because a negative number multiplied by another negative may result in a large positve number. Therefore IMP to check max between currMax and currMin.
2129

22-
currMax = max(max(currMax * nums[i], currMin * nums[i]), nums[i]);
23-
currMin = min(min(currMin * nums[i], temp * nums[i]), nums[i]);
24-
25-
result = max(result, currMax);
30+
ans = max(currMax,ans); //global result or maxUntilNow
2631
}
27-
28-
return result;
32+
return ans;
2933
}
34+
35+
3036
};

0 commit comments

Comments
 (0)