Given an array that contains both positive and negative integers, the task is to find the product of the maximum product subarray.
Examples:
Input: arr[] = {6, -3, -10, 0, 2}
Output: 180
Explanation: The subarray is {6, -3, -10}
Input: arr[] = {-1, -3, -10, 0, 60}
Output: 60
Explanation: The subarray is {60}
Maximum Product Subarray by Traverse Over Every Contiguous Subarray:
The idea is to traverse over every contiguous subarray, find the product of each of these subarrays and return the maximum product from these results.
Follow the below steps to solve the problem:
- Run a nested for loop to generate every subarray
- Calculate the product of elements in the current subarray
- Return the maximum of these products calculated from the subarrays
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxSubarrayProduct( int arr[], int n)
{
int result = arr[0];
for ( int i = 0; i < n; i++) {
int mul = arr[i];
for ( int j = i + 1; j < n; j++) {
result = max(result, mul);
mul *= arr[j];
}
result = max(result, mul);
}
return result;
}
int main()
{
int arr[] = { 1, -2, -3, 0, 7, -8, -2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Maximum Sub array product is "
<< maxSubarrayProduct(arr, n);
return 0;
}
|
C
#include <stdio.h>
int max( int num1, int num2)
{
return (num1 > num2) ? num1 : num2;
}
int maxSubarrayProduct( int arr[], int n)
{
int result = arr[0];
for ( int i = 0; i < n; i++) {
int mul = arr[i];
for ( int j = i + 1; j < n; j++) {
result = max(result, mul);
mul *= arr[j];
}
result = max(result, mul);
}
return result;
}
int main()
{
int arr[] = { 1, -2, -3, 0, 7, -8, -2 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "Maximum Sub array product is %d " ,
maxSubarrayProduct(arr, n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int maxSubarrayProduct( int arr[])
{
int result = arr[ 0 ];
int n = arr.length;
for ( int i = 0 ; i < n; i++) {
int mul = arr[i];
for ( int j = i + 1 ; j < n; j++) {
result = Math.max(result, mul);
mul *= arr[j];
}
result = Math.max(result, mul);
}
return result;
}
public static void main(String[] args)
{
int arr[] = { 1 , - 2 , - 3 , 0 , 7 , - 8 , - 2 };
System.out.println( "Maximum Sub array product is "
+ maxSubarrayProduct(arr));
}
}
|
Python3
def maxSubarrayProduct(arr, n):
result = arr[ 0 ]
for i in range (n):
mul = arr[i]
for j in range (i + 1 , n):
result = max (result, mul)
mul * = arr[j]
result = max (result, mul)
return result
arr = [ 1 , - 2 , - 3 , 0 , 7 , - 8 , - 2 ]
n = len (arr)
print ( "Maximum Sub array product is" , maxSubarrayProduct(arr, n))
|
C#
using System;
class GFG {
static int maxSubarrayProduct( int [] arr)
{
int result = arr[0];
int n = arr.Length;
for ( int i = 0; i < n; i++) {
int mul = arr[i];
for ( int j = i + 1; j < n; j++) {
result = Math.Max(result, mul);
mul *= arr[j];
}
result = Math.Max(result, mul);
}
return result;
}
public static void Main(String[] args)
{
int [] arr = { 1, -2, -3, 0, 7, -8, -2 };
Console.Write( "Maximum Sub array product is "
+ maxSubarrayProduct(arr));
}
}
|
Javascript
<script>
function maxSubarrayProduct(arr, n)
{
let result = arr[0];
for (let i = 0; i < n; i++)
{
let mul = arr[i];
for (let j = i + 1; j < n; j++)
{
result = Math.max(result, mul);
mul *= arr[j];
}
result = Math.max(result, mul);
}
return result;
}
let arr = [ 1, -2, -3, 0, 7, -8, -2 ];
let n = arr.length;
document.write( "Maximum Sub array product is "
+ maxSubarrayProduct(arr, n));
</script>
|
Output
Maximum Sub array product is 112
Time Complexity: O(N2)
Auxiliary Space: O(1)
The idea is to use Kadane’s algorithm and maintain 3 variables max_so_far, max_ending_here & min_ending_here. Iterate the indices 0 to N-1 and update the variables such that:
- max_ending_here = maximum(arr[i], max_ending_here * arr[i], min_ending_here[i]*arr[i])
- min_ending_here = maximum(arr[i], max_ending_here * arr[i], min_ending_here[i]*arr[i])
- update the max_so_far with the maximum value for each index.
return max_so_far as the result.
Follow the below steps to solve the problem:
- Use 3 variables, max_so_far, max_ending_here & min_ending_here
- For every index, the maximum number ending at that index will be the maximum(arr[i], max_ending_here * arr[i], min_ending_here[i]*arr[i])
- Similarly, the minimum number ending here will be the minimum of these 3
- Thus we get the final value for the maximum product subarray
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxSubarrayProduct( int arr[], int n)
{
int max_ending_here = arr[0];
int min_ending_here = arr[0];
int max_so_far = arr[0];
for ( int i = 1; i < n; i++) {
int temp = max({ arr[i], arr[i] * max_ending_here,
arr[i] * min_ending_here });
min_ending_here
= min({ arr[i], arr[i] * max_ending_here,
arr[i] * min_ending_here });
max_ending_here = temp;
max_so_far = max(max_so_far, max_ending_here);
}
return max_so_far;
}
int main()
{
int arr[] = { 1, -2, -3, 0, 7, -8, -2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Maximum Sub array product is "
<< maxSubarrayProduct(arr, n);
return 0;
}
|
C
#include <stdio.h>
int max( int num1, int num2)
{
return (num1 > num2) ? num1 : num2;
}
int min( int num1, int num2)
{
return (num1 > num2) ? num2 : num1;
}
int maxSubarrayProduct( int arr[], int n)
{
int max_ending_here = arr[0];
int min_ending_here = arr[0];
int max_so_far = arr[0];
for ( int i = 1; i < n; i++) {
int temp
= max(max(arr[i], arr[i] * max_ending_here),
arr[i] * min_ending_here);
min_ending_here
= min(min(arr[i], arr[i] * max_ending_here),
arr[i] * min_ending_here);
max_ending_here = temp;
max_so_far = max(max_so_far, max_ending_here);
}
return max_so_far;
}
int main()
{
int arr[] = { 1, -2, -3, 0, 7, -8, -2 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "Maximum Sub array product is %d" ,
maxSubarrayProduct(arr, n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int maxSubarrayProduct( int arr[], int n)
{
int max_ending_here = arr[ 0 ];
int min_ending_here = arr[ 0 ];
int max_so_far = arr[ 0 ];
for ( int i = 1 ; i < n; i++) {
int temp = Math.max(
Math.max(arr[i], arr[i] * max_ending_here),
arr[i] * min_ending_here);
min_ending_here = Math.min(
Math.min(arr[i], arr[i] * max_ending_here),
arr[i] * min_ending_here);
max_ending_here = temp;
max_so_far
= Math.max(max_so_far, max_ending_here);
}
return max_so_far;
}
public static void main(String args[])
{
int [] arr = { 1 , - 2 , - 3 , 0 , 7 , - 8 , - 2 };
int n = arr.length;
System.out.printf( "Maximum Sub array product is %d" ,
maxSubarrayProduct(arr, n));
}
}
|
Python3
def maxSubarrayProduct(arr, n):
max_ending_here = arr[ 0 ]
min_ending_here = arr[ 0 ]
max_so_far = arr[ 0 ]
for i in range ( 1 , n):
temp = max ( max (arr[i], arr[i] * max_ending_here),
arr[i] * min_ending_here)
min_ending_here = min (
min (arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here)
max_ending_here = temp
max_so_far = max (max_so_far, max_ending_here)
return max_so_far
arr = [ 1 , - 2 , - 3 , 0 , 7 , - 8 , - 2 ]
n = len (arr)
print (f "Maximum Sub array product is {maxSubarrayProduct(arr, n)}" )
|
C#
using System;
class GFG {
static int maxSubarrayProduct( int [] arr)
{
int max_ending_here = arr[0];
int min_ending_here = arr[0];
int max_so_far = arr[0];
for ( int i = 1; i < arr.Length; i++) {
int temp = Math.Max(
Math.Max(arr[i], arr[i] * max_ending_here),
arr[i] * min_ending_here);
min_ending_here = Math.Min(
Math.Min(arr[i], arr[i] * max_ending_here),
arr[i] * min_ending_here);
max_ending_here = temp;
max_so_far
= Math.Max(max_so_far, max_ending_here);
}
return max_so_far;
}
public static void Main()
{
int [] arr = { 1, -2, -3, 0, 7, -8, -2 };
Console.WriteLine( "Maximum Sub array product is "
+ maxSubarrayProduct(arr));
}
}
|
Javascript
<script>
function maxSubarrayProduct(arr, n)
{
let max_ending_here = arr[0];
let min_ending_here = arr[0];
let max_so_far = arr[0];
for (let i = 1; i < n; i++)
{
let temp = Math.max(Math.max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here);
min_ending_here = Math.min(Math.min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here);
max_ending_here = temp;
max_so_far = Math.max(max_so_far, max_ending_here);
}
return max_so_far;
}
let arr = [ 1, -2, -3, 0, 7, -8, -2 ]
let n = arr.length
document.write( "Maximum Sub array product is " +maxSubarrayProduct(arr, n));
</script>
|
Output
Maximum Sub array product is 112
Time Complexity: O(N)
Auxiliary Space: O(1)
Maximum Product Subarray using Traversal From Starting and End of an Array:
We will follow a simple approach that is to traverse and multiply elements and if our value is greater than the previously stored value then store this value in place of the previously stored value. If we encounter “0” then make products of all elements till now equal to 1 because from the next element, we will start a new subarray.
But what can be the problem with that?
Problem will occur when our array will contain odd no. of negative elements. In that case, we have to reject anyone negative element so that we can even no. of negative elements and their product can be positive. Now since we are considering subarray so we can’t simply reject any one negative element. We have to either reject the first negative element or the last negative element.
But if we will traverse from starting then only the last negative element can be rejected and if we traverse from the last then the first negative element can be rejected. So we will traverse from both the end and from both the traversal we will take answer from that traversal only which will give maximum product subarray.
So actually we will reject that negative element whose rejection will give us the maximum product’s subarray.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long int maxSubarrayProduct( int arr[], int n)
{
long long ans=INT_MIN;
long long product=1;
for ( int i=0;i<n;i++){
product*=arr[i];
ans=max(ans,product);
if (arr[i]==0){product=1;}
}
product=1;
for ( int i=n-1;i>=0;i--){
product*=arr[i];
ans=max(ans,product);
if (arr[i]==0){product=1;}
}
return ans;
}
int main()
{
int arr[] = { 1, -2, -3, 0, 7, -8, -2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Maximum Sub array product is "
<< maxSubarrayProduct(arr, n);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static long maxSubarrayProduct( int [] arr, int n)
{
long ans = Integer.MIN_VALUE;
long product = 1 ;
for ( int i = 0 ; i < n; i++) {
product *= arr[i];
ans = Math.max(ans, product);
if (arr[i] == 0 ) {
product = 1 ;
}
}
product = 1 ;
for ( int i = n - 1 ; i >= 0 ; i--) {
product *= arr[i];
ans = Math.max(ans, product);
if (arr[i] == 0 ) {
product = 1 ;
}
}
return ans;
}
public static void main(String[] args)
{
int [] arr = { 1 , - 2 , - 3 , 0 , 7 , - 8 , - 2 };
int n = arr.length;
System.out.println( "Maximum Subarray product is "
+ maxSubarrayProduct(arr, n));
}
}
|
Python3
import sys
def maxSubarrayProduct(arr, n):
ans = - sys.maxsize - 1
product = 1
for i in range (n):
product * = arr[i]
ans = max (ans, product)
if arr[i] = = 0 :
product = 1
product = 1
for i in range (n - 1 , - 1 , - 1 ):
product * = arr[i]
ans = max (ans, product)
if arr[i] = = 0 :
product = 1
return ans
arr = [ 1 , - 2 , - 3 , 0 , 7 , - 8 , - 2 ]
n = len (arr)
print ( "Maximum Subarray product is" , maxSubarrayProduct(arr, n))
|
C#
using System;
public class MainClass {
public static int MaxSubarrayProduct( int [] arr, int n)
{
int ans
= int .MinValue;
int product = 1;
for ( int i = 0; i < n; i++) {
product *= arr[i];
ans = Math.Max(
ans, product);
if (arr[i] == 0) {
product = 1;
}
}
product = 1;
for ( int i = n - 1; i >= 0; i--) {
product *= arr[i];
ans = Math.Max(ans, product);
if (arr[i] == 0) {
product = 1;
}
}
return ans;
}
public static void Main()
{
int [] arr = { 1, -2, -3, 0, 7, -8, -2 };
int n = arr.Length;
Console.WriteLine( "Maximum Subarray product is "
+ MaxSubarrayProduct(arr, n));
}
}
|
Javascript
function maxSubarrayProduct(arr, n) {
let ans = -Infinity;
let product = 1;
for (let i = 0; i < n; i++) {
product *= arr[i];
ans = Math.max(ans, product);
if (arr[i] === 0) {
product = 1;
}
}
product = 1;
for (let i = n - 1; i >= 0; i--) {
product *= arr[i];
ans = Math.max(ans, product);
if (arr[i] === 0) {
product = 1;
}
}
return ans;
}
const arr = [1, -2, -3, 0, 7, -8, -2];
const n = arr.length;
console.log(`Maximum Subarray product is ${maxSubarrayProduct(arr, n)}`);
|
Output
Maximum Sub array product is 112
Time Complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
25 Oct, 2023
Like Article
Save Article