Maximum Product Subarray

Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
class Solution {
public:
int maxProduct(vector<int>& nums) {
int left=1,right=1;
int ans=INT_MIN;
int n=nums.size();
for(int i=0;i<n;i++){
left=left*nums[i];//calculating prod from left side
right=right*nums[n-i-1];//calculating prod from right side
ans=max(ans,max(left,right));
if(left==0){
left=1;
}if(right==0){
right=1;
}

}
return ans;
}
};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store