Maximum Product Subarray

--help cse
1 min readJun 18, 2022

Problem Statement:

Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

A subarray is a contiguous subsequence of the array.

TestCase:

Example 1:

Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

CODE:

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;
}
};

OUTPUT:

Your input

[2,3,-2,4]

Output:

6

Related problem:

Maximum Subarray

House Robber

Product of Array Except Self

Maximum Product of Three Numbers

Subarray Product Less Than K

written by S.L.More

--

--