Skip to content

Commit 5add706

Browse files
authored
Merge pull request SjxSubham#129 from Subratkb02/main
152. Maximum Product Subarray
2 parents 890a341 + 423b90a commit 5add706

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

152. Maximum-Product-Subarray.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// 152. Maximum Product Subarray
2+
// By Traversing in Both Directions
3+
// Time Complexity - O(n) and Space Complexity - O(1)
4+
class Solution {
5+
public:
6+
int maxProduct(vector<int>& nums) {
7+
int n = nums.size();
8+
int maxi = INT_MIN;
9+
int ltr = 1, rtl = 1;
10+
for(int i=0; i<n; i++){
11+
if(ltr == 0){
12+
ltr = 1;
13+
}
14+
if(rtl == 0){
15+
rtl = 1;
16+
}
17+
18+
ltr *= nums[i];
19+
int j = n-i-1;
20+
rtl *= nums[j];
21+
22+
maxi = max({ltr,rtl,maxi});
23+
}
24+
return maxi;
25+
}
26+
};

0 commit comments

Comments
 (0)