Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Subarray With Maximum Product

Moderate
0/80
profile
Contributed by
80 upvotes

Problem statement

Given an array ‘Arr’ that has ‘N’ elements. You have to find the subarray of ‘Arr’ that has the largest product. You must return the product of the subarray with the maximum product.


For example:
When ‘N’ = 5, and ‘Arr’ = {-2, 3, -4, 0}
The subarrays of ‘Arr’ are:
{-2}, {-2, 3}, {-2, 3, -4}, {-2, 3, -4, 0}, {3}, {3, -4}, {3, -4, 0}, {-4}, {-4, 0}, {0}.
Among these, {-2, 3, -4} is the subarray having the maximum product equal to 24.
Hence, the answer is 24.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains an integer ‘N’, denoting the size of ‘Arr’.
The second line contains ‘N’ integers denoting the elements of ‘Arr’.
Output Format:
You must return an integer, denoting the product of the subarray with the maximum product.
Sample Input 1:
4
1 -2 3 -4
Sample Output 1:
24
Explanation Of Sample Input 1:
Given, ‘Arr’ = {1, -2, 3, -4}. The subarrays of ‘Arr’ are: 
{{1}, {1, -2}, {1, -2, 3}, {1, -2, 3, -4}, {-2}, {-2, 3}, {-2, 3, -4}, {3}, {3, -4}, {-4}}.
Among these subarrays, {1, -2, 3, -4} and {-2, 3, -4} have the maximum product, equal to 24.
Hence, the answer is 24.
Sample Input 2:
5
-1 3 0 -4 3
Sample Output 2:
3
Constraints:
1 <= N <= 10^5
-100 <= Arr[i] <= 100

-10^9 <= The product of elements of any subarray <= 10^9.
The sum of ‘N’ over all test cases <= 10^5.
Time Limit: 1-sec
Hint

Try iterating over all subarrays.

Approaches (2)
Brute Force

Approach:

We iterate over all subarrays of ‘Arr’ and compare its product with the largest product found so far. Likewise, we return the product of the subarray with the maximum product.

 

Algorithm:

  • Ans = INT_MIN
  • for ‘i’ from 0 to ‘N - 1’:
    • CurrentProduct = 1
    • for ‘j’ from ‘i’ to ‘N - 1’:
      • CurrentProduct *= Arr[j]
      • Ans = max(Ans, CurrentProduct)
  • return ‘Ans’
Time Complexity

O(N ^ 2), where ‘N’ is the number of elements in ‘Arr’.

 

We are iterating over all subarrays in O(N * N) time and the multiplication and comparison operations take O(1) time. Hence, the overall time complexity of this solution is O(N * N).

Space Complexity

O(1)

 

Since we are not using any extra space, the overall space complexity of this solution is O(1).

Code Solution
(100% EXP penalty)
Subarray With Maximum Product
All tags
Sort by
Search icon

Interview problems

batter than 100% "Subarray With Maximum Product" using Kadane's Algorithm

#include<bits/stdc++.h>

using namespace std;

 

int subarrayWithMaxProduct(vector<int> &arr){

    // Write your code here.

    int prod1 = arr[0], prod2 = arr[0], result = arr[0];

    int n = arr.size();

    for(int i=1; i<n; i++){

          int temp = max({arr[i], prod1*arr[i], prod2*arr[i]});

          prod2 = min({arr[i], prod1*arr[i], prod2*arr[i]});

          prod1 = temp;

          result = max(result, prod1);

        }

    return result;

}

38 views
0 replies
1 upvote

Interview problems

T,C o(n)

#include<vector>

#include <climits> // Include this header for INT_MIN

 

int subarrayWithMaxProduct(vector<int> &arr) {

  int ans = INT_MIN;

  int pref = 1; int suff = 1; 

  int n = arr.size();

 

  for (int i = 0; i < n; i++){

    if(pref == 0) pref = 1;

    if(suff == 1) suff = 1; 

    pref = pref * arr[i]; 

    suff = suff * arr[n-i-1]; 

    ans = max(ans, max(pref, suff));

  }

  return ans; 

}

20 views
0 replies
0 upvotes

Interview problems

Just one variable addition to Kadane's algo!

/*I hope this approach is right, regardless of this solution getting AC.*/

int subarrayWithMaxProduct(vector<int> &arr){
    // Write your code here.
    //{-2, 3, -4, 0} ans = 24(-2*3*-4)
    int productSoFar = 1, positiveProductSoFar = 1, maxProduct = INT_MIN, ansSoFar = 1;
    for(auto n: arr)
    {
        productSoFar *= n;
        positiveProductSoFar *= n;
        ansSoFar = max(n, max(productSoFar, positiveProductSoFar));
        maxProduct = max(maxProduct, ansSoFar);


        if(productSoFar == 0)
            productSoFar = 1;
        if(positiveProductSoFar <= 0)
            positiveProductSoFar = 1;
    }
    return maxProduct;
}
12 views
0 replies
0 upvotes

Interview problems

c++ solution Brute/Optimal

 

#include<bits/stdc++.h>

 

int subarrayWithMaxProduct(vector<int> &arr){

//  // Write your code here.

//  int maxi=INT_MIN;

//  for(int i=0;i<arr.size();i++){

//      int prod=1;

//      for(int j=i;j<arr.size();j++){

// prod=prod*arr[j];

// maxi=max(prod,maxi);

//      }

        

//  }

//  return maxi;                //O(n^2)

//------------------------

int pre=1,suff=1;

int ans=INT_MIN;

int n=arr.size();

for(int i=0;i<n;i++){

    if(pre==0)pre=1;

    if(suff==0)suff=1;

    pre=pre*arr[i];

    suff=suff*arr[n-i-1];

    ans=max(ans,max(pre,suff));

}

return ans;

}

//O(n)=TC, SC=O(1)

23 views
0 replies
0 upvotes

Interview problems

🔥 Max Product of Subarray: Dual Traversal Magic with Prefix & Suffix! 🔄

☄️Intuition

The idea is to find the maximum product of a subarray in the given array of integers. This problem can be tricky because negative numbers can flip the product, and we may have to consider both the prefix (left to right) and suffix (right to left) arrays to make sure we don't miss any potential maximum product.

🧠Approach
  1. Two Traversals: Instead of maintaining only one running product, we maintain two:

One for the prefix product, going from left to right.

Another for the suffix product, going from right to left.

Reset on Zero: Since a product becomes 0 when any element is zero, we reset the product to 1 when encountering a zero.

Keep Track of Max Product: During each traversal, we keep updating the maximum product encountered so far.

🛠️ How it works:

We keep two products:

Prefix: Starts multiplying numbers from the left.

Suffix: Starts multiplying numbers from the right.

At each step, we check the product of both the prefix and suffix and update the maximum product found.

If we encounter a zero, the product will be reset to 1, since multiplying by zero ruins the subarray product.

⏳Complexity
  • Time complexity:

O(n): We are making only a single pass through the array, which means the time complexity is linear.

  • Space complexity:

O(1): We only use a few extra variables (prefix, suffix, max), so the space complexity is constant.

 

public class Solution {
    public static int subarrayWithMaxProduct(int []arr){
        // Write your code here.
        int n=arr.length;
        int prefix=1;
        int suffix=1;
        int max=Integer.MIN_VALUE;
        for(int i=0;i<n;i++)
        {
            if(prefix==0)
            prefix=1;
            else if(suffix==0)
            suffix=1;

            suffix=suffix*arr[i];
            prefix=prefix*arr[n-i-1];
            max=Math.max(max,Math.max(prefix,suffix));
        }
        return max;
    }
}
10 views
0 replies
0 upvotes

Interview problems

13 ms SOlutionj

#include<vector>

#include <bits/stdc++.h>

 

int subarrayWithMaxProduct(vector<int> &arr){

    // Write your code here.

    int prefix = 1;

    int suffix = 1;

    int ans = INT_MIN;

    int  n = arr.size();

    for(int i = 0; i < n ; i++){

        if(prefix == 0) prefix= 1;

        if(suffix == 0) suffix = 1;

 

        prefix = prefix * arr[i];

        suffix = suffix * arr[n-i-1];

        ans = max(ans , max(prefix,suffix));

    }

 

    return ans;

 

}

33 views
0 replies
0 upvotes

Interview problems

C++ Solution || Optimized Code || Subarray With Maximum Product

#include<vector>

#include<stdio.h>

 

int subarrayWithMaxProduct(vector<int> &arr){

    // Write your code here.

    int n = arr.size();

    int ans = 0;

    int pre = 1 , suff = 1;

    for(int i=0 ; i<n ; i++){

        if(pre == 0) pre =1;

        if(suff == 0) suff =1;

 

        pre = pre*arr[i];

        suff = suff*arr[n-i-1];

        ans = max(ans , max(pre , suff));

 

    }

    return ans;

}

64 views
0 replies
0 upvotes

Interview problems

optimal c++ code

#include<bits/stdc++.h>

int subarrayWithMaxProduct(vector<int> &arr){

    int pre=1,suff=1;

    int n = arr.size();

    int ans = INT_MIN;

    for(int i=0;i<n;i++) {

        pre = pre*arr[i];

        suff = suff*arr[n-i-1];

        if(pre == 0) pre = 1;

        if(suff == 0) suff = 1;

        ans = max(ans,max(pre,suff));

    }

    return ans;

}

42 views
0 replies
0 upvotes

Interview problems

SIMPLE EASY APPROACH 🎯 (BEATS 100%)

#include <climits>

int subarrayWithMaxProduct(vector<int> &arr){

// Write your code here.

int prefi=1;

int suf=1;

int maxi=INT_MIN;

int n=arr.size();

for(int i=0;i<arr.size();i++)

{

if(prefi==0) prefi=1;

if(suf==0) suf=1;

 

prefi=prefi*arr[i];

suf=suf*arr[n-i-1];

 

maxi=max(maxi,max(prefi,suf));

}

return maxi;

}

88 views
1 reply
0 upvotes

Interview problems

Most Intuitive One (optimal solution)

import java.util.*;

public class Solution {

    public static int subarrayWithMaxProduct(int []arr){

        // Write your code here.

        int ans = Integer.MIN_VALUE;

        int n = arr.length;

        int pre =1, suff =1;

        for(int  i = 0 ;i< n;i++){

            if(pre == 0) pre =1;

            if(suff == 0 ) suff = 1;

 

            pre = pre *arr[i];

            suff = suff * arr[n-i-1];

            ans = Math.max(ans,Math.max(pre,suff));

        }

        return ans;

    }

}

java

85 views
0 replies
1 upvote
Full screen
Console