Maximum Product Subarray | Practice | GeeksforGeeks

Given an array Arr[] that contains N integers (may be positive, negative or zero). Find the product of the maximum product subarray.
Example 1:
Input:
N = 5
Arr[] = {6, -3, -10, 0, 2}
Output: 180
Explanation: Subarray with maximum product
is [6, -3, -10] which gives product as 180.

Example 2:
Input:
N = 6
Arr[] = {2, 3, 4, 5, -1, 0}
Output: 120
Explanation: Subarray with maximum product
is [2, 3, 4, 5] which gives product as 120.

Your Task:
You don't need to read input or print anything. Your task is to complete the function maxProduct() which takes the array of integers arr and n as parameters and returns an integer denoting the answer.
Note: Use 64-bit integer data type to avoid overflow.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 500
-102 ≤ Arri ≤ 102
0
niravramotiya0033 days ago
import sys
class Solution:
def maxProduct(self,arr, n):
 front=-sys.maxsize - 1
 back=-sys.maxsize - 1
 fp=0
 sf=1
 sb=1
 bp=n-1
 while(fp<n):
     sf=sf*arr[fp]
     sb=sb*arr[bp]
     if arr[fp]==0:
         sf=1
     if arr[bp]==0:
         sb=1
     if front<sf:
         front=sf
     if back<sb:
         back=sb
     fp+=1
     bp-=1
    if front>back:
        return front
    else:
        return back
    return 0
0
jeffprivate03136 days ago
Kinda hardcoded the solution
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends//User function template for C++class Solution{public:
// Function to find maximum product subarraylong long maxProduct(vector<int> arr, int n) {    long long tm=1;    long long gm=numeric_limits<long long>::min();    int flag=-1;//positive    int l=0;    int r=-1;    for(int i=0;i<n;i++){//for recording positive or negative        if(arr[i]==0){            if(flag==-1){                gm=max(gm,(long long)0);            }else{                if(l==r){                    gm=max(gm,(long long)arr[l]);                    l=i+1;                    tm=1;                    flag=-1;                    continue;                }                            long long ttm=tm;                int tl=l;                int tr=r;                while(ttm<0 and tl<tr){                    ttm/=arr[tl];                    tl++;                    gm=max(gm,ttm);                }                gm=max(gm,ttm);                ttm=tm;                tl=l;                while(ttm<0 and tr>tl){                    ttm/=arr[tr];                    tr--;                    gm=max(gm,ttm);                }                gm=max(gm,ttm);            }            tm=1;            flag=-1;            l=i+1;        }else{            tm*=arr[i];            r=max(i,r);            if(flag==-1){                flag=1;//changed, not consecutive zeroes            }        }        //cout<<tm<<" "<<l<<" "<<r<<endl;    }       if(flag!=-1){           if(l==r){           gm=max(gm,(long long)arr[r]);        }else{        //cout<<tm<<" "<<l<<" "<<r<<endl;        long long ttm=tm;        int tl=l;        int tr=r;        while(ttm<0 and tl<tr){            ttm/=arr[tl];            tl++;            gm=max(ttm,gm);        }        gm=max(gm,ttm);        ttm=tm;        tl=l;        while(ttm<0 and tr>tl){           ttm/=arr[tr];           tr--;        }        gm=max(gm,ttm);        }   }    return gm;    // code here}};
// { Driver Code Starts.
int main() {   int t;   cin >> t;   while (t--) {       int n, i;       cin >> n;       vector<int> arr(n);       for (i = 0; i < n; i++) {           cin >> arr[i];       }       Solution ob;       auto ans = ob.maxProduct(arr, n);       cout << ans << "\n";   }   return 0;}  // } Driver Code Ends
0
kumarbarnwalashutosh1 week ago
In the Example1 the maximum product as I observed is 360 ( product of [6,-3,-10,2]), but it says 180. Where am I wrong can somebody tell me.
 
0
rohanmeher1642 weeks ago
// java solution
 
class Solution {   // Function to find maximum product subarray   long maxProduct(int[] arr, int n) {      long product=1;      long maxproduct=arr[0];    for(int i=0;i<n; i++)    {        product*=arr[i];        maxproduct=Math.max(maxproduct, product);        if(product==0)        {            product=1;        }    }    product=1;    for(int i= n-1; i>=0; i--)    {        product*=arr[i];        maxproduct=Math.max(maxproduct, product);        if(product==0)        {            product=1;        }    }    return maxproduct;   }}
+3
tarrasridhar11542 weeks ago
Time : 0.68/1.86
long long maxProduct(vector<int> arr, int n) {
	   
	   long long int maxproduct=INT_MIN;
	   long long int product=1;
	    for(int i=0;i<n; i++)
	    {
	        product*=arr[i];
	        maxproduct=max(maxproduct, product);
	        if(product==0)
	        {
	            product=1;
	        }
	    }
	    product=1;
	    for(int i= n-1; i>=0; i--)
	    {
	        product*=arr[i];
	        maxproduct=max(maxproduct, product);
	        if(product==0)
	        {
	            product=1;
	        }
	    }
	    return maxproduct;
	
	}
 
 
0
raonirajkumar262 weeks ago
Python Solution
  def maxProduct(self,arr, n):       minVal = arr[0]       maxVal = arr[0]       maxProduct = arr[0]       for i in range(1, n):           if (arr[i] < 0):               maxVal,minVal = minVal,maxVal           # print("1",arr[i],minVal,maxVal,maxProduct)           maxVal = max(arr[i], maxVal * arr[i])           minVal = min(arr[i], minVal * arr[i])           maxProduct = max(maxProduct, maxVal)           # print("2",arr[i],minVal,maxVal,maxProduct)       return maxProduct
+1
joyrockok3 weeks ago
class Solution {   // Function to find maximum product subarray   long maxProduct(int[] arr, int n) {       // code here        long MaxSumOfSubArr=0;    long Max=0, Min=0;        MaxSumOfSubArr = Max = Min = arr[0];        for(int i=1; i<n; i++) {          long temp = Math.max(Max*arr[i], Min*arr[i]);     Min = Math.min(Max*arr[i], Min*arr[i]);     Max = temp;          Max = Math.max(arr[i], Max);     Min = Math.min(arr[i], Min);          MaxSumOfSubArr = Math.max(MaxSumOfSubArr, Max);    }        return MaxSumOfSubArr;   }}
+3
harshscode3 weeks ago
best approach..
 long long maxProduct(vector<int> a, int n) {  long long prdt=1,maxprdt=INT_MIN;  //    if -ve element or zero is at right side then we found maximun from left    for(int i=0;i<n;i++)  {      prdt*=a[i];      maxprdt=max(maxprdt,prdt);      if(prdt==0)      prdt=1;  }  //    if -ve element is from left side then we got maximum product from right  prdt=1;   for(int i=n-1;i>=0;i--)  {      prdt*=a[i];      maxprdt=max(maxprdt,prdt);      if(prdt==0)      prdt=1;  }       return maxprdt;
 
+2
adityagagtiwari3 weeks ago
Pepcoding Intuitive solution.!!
 
class Solution {
   // Function to find maximum product subarray
   long maxProduct(int[] arr, int n) {
       // code here
       //an important claim is that the MPS will be starting from the beginning or from the end 
       //it CANNOT be inbetween the array . This can be proved using contradiction
       long currprod = 1;
       long maxprod = Integer.MIN_VALUE;
       for(int i=0;i<n;i++)
       {
           currprod*=arr[i];
           maxprod = Math.max(maxprod,currprod);
          //here zero act as a clearscreen which would give you one maxprod value
          //after each zero fresh current product should be calculated as using zero as a
          //part of subarray will make your product value into a BIGASS ZERO.
           if(currprod==0)
            currprod = 1;
            
       }
       currprod = 1;
        for(int i=n-1;i>=0;i--)
       {
           currprod*=arr[i];
           maxprod = Math.max(maxprod,currprod);
           if(currprod==0)
            currprod = 1;
            
       }
      return maxprod; 
   }
}
-1
roopbhawana3153 weeks ago
pyrhon solution
 
def maxProduct(self,arr, n):    ans = mx = mn = arr[0] for i in range(1,n):     if i == 0:         mx=1         mn=1         continue     else:         temp1=arr[i]*mx         temp2=arr[i]*mn         mx=max(temp1,temp2)         mx=max(mx,arr[i])         mn=min(temp1,temp2)         mn=min(mn,arr[i])         ans=max(ans,mx) return ans
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.