Maximize product of subarray sum with its minimum element
Last Updated :
11 Jul, 2022
Given an array arr[] consisting of N positive integers, the task is to find the maximum product of subarray sum with the minimum element of that subarray.
Examples:
Input: arr[] = {3, 1, 6, 4, 5, 2}
Output: 60
Explanation:
The required maximum product can be obtained using subarray {6, 4, 5}
Therefore, maximum product = (6 + 4 + 5) * (4) = 60
Input: arr[] = {4, 1, 2, 9, 3}
Output: 81
Explanation:
The required maximum product can be obtained using subarray {9}
Maximum product = (9)* (9) = 81
Naive Approach: The simplest approach to solve the problem is to generate all subarrays of the given array and for each subarray, calculate the sum of the subarray, and multiply it with the minimum element in the subarray. Update the maximum product by comparing it with the product calculated. Finally, print the maximum product obtained after processing all the subarray.
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using a Stack and Prefix Sum Array. The idea is to use the stack to get the index of nearest smaller elements on the left and right of each element. Now, using these, the required product can be obtained. Follow the steps below to solve the problem:
- Initialize an array presum[] to store all the resultant prefix sum array of the given array.
- Initialize two arrays l[] and r[] to store the index of the nearest left and right smaller elements respectively.
- For every element arr[i], calculate l[i] and r[i] using a stack.
- Traverse the given array and for each index i, the product can be calculated by:
arr[i] * (presum[r[i]] – presum[l[i]-1])
- Print the maximum product after completing all the above steps
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void maxValue( int a[], int n)
{
int presum[n];
presum[0] = a[0];
for ( int i = 1; i < n; i++)
{
presum[i] = presum[i - 1] + a[i];
}
int l[n], r[n];
stack< int > st;
for ( int i = 1; i < n; i++)
{
while (!st.empty() &&
a[st.top()] >= a[i])
st.pop();
if (!st.empty())
l[i] = st.top() + 1;
else
l[i] = 0;
st.push(i);
}
while (!st.empty())
st.pop();
for ( int i = n - 1; i >= 0; i--)
{
while (!st.empty() &&
a[st.top()] >= a[i])
st.pop();
if (!st.empty())
r[i] = st.top() - 1;
else
r[i] = n - 1;
st.push(i);
}
int maxProduct = 0;
int tempProduct;
for ( int i = 0; i < n; i++)
{
tempProduct = a[i] * (presum[r[i]] -
(l[i] == 0 ? 0 :
presum[l[i] - 1]));
maxProduct = max(maxProduct,
tempProduct);
}
cout << maxProduct;
}
int main()
{
int n = 6;
int arr[] = { 3, 1, 6, 4, 5, 2 };
maxValue(arr, n);
}
|
Java
import java.util.*;
class GFG {
public static void
maxValue( int [] a, int n)
{
int [] presum = new int [n];
presum[ 0 ] = a[ 0 ];
for ( int i = 1 ; i < n; i++) {
presum[i] = presum[i - 1 ] + a[i];
}
int [] l = new int [n], r = new int [n];
Stack<Integer> st = new Stack<>();
for ( int i = 1 ; i < n; i++) {
while (!st.isEmpty()
&& a[st.peek()] >= a[i])
st.pop();
if (!st.isEmpty())
l[i] = st.peek() + 1 ;
else
l[i] = 0 ;
st.push(i);
}
st.clear();
for ( int i = n - 1 ; i >= 0 ; i--) {
while (!st.isEmpty()
&& a[st.peek()] >= a[i])
st.pop();
if (!st.isEmpty())
r[i] = st.peek() - 1 ;
else
r[i] = n - 1 ;
st.push(i);
}
int maxProduct = 0 ;
int tempProduct;
for ( int i = 0 ; i < n; i++) {
tempProduct
= a[i]
* (presum[r[i]]
- (l[i] == 0 ? 0
: presum[l[i] - 1 ]));
maxProduct
= Math.max(maxProduct,
tempProduct);
}
System.out.println(maxProduct);
}
public static void main(String[] args)
{
int [] arr = { 3 , 1 , 6 , 4 , 5 , 2 };
maxValue(arr, arr.length);
}
}
|
Python3
def maxValue(a, n):
presum = [ 0 for i in range (n)]
presum[ 0 ] = a[ 0 ]
for i in range ( 1 , n, 1 ):
presum[i] = presum[i - 1 ] + a[i]
l = [ 0 for i in range (n)]
r = [ 0 for i in range (n)]
st = []
for i in range ( 1 , n):
while ( len (st) and
a[st[ len (st) - 1 ]] > = a[i]):
st.remove(st[ len (st) - 1 ])
if ( len (st)):
l[i] = st[ len (st) - 1 ] + 1 ;
else :
l[i] = 0
st.append(i)
while ( len (st)):
st.remove(st[ len (st) - 1 ])
i = n - 1
while (i > = 0 ):
while ( len (st) and
a[st[ len (st) - 1 ]] > = a[i]):
st.remove(st[ len (st) - 1 ])
if ( len (st)):
r[i] = st[ len (st) - 1 ] - 1
else :
r[i] = n - 1
st.append(i)
i - = 1
maxProduct = 0
for i in range (n):
if l[i] = = 0 :
tempProduct = (a[i] *
presum[r[i]])
else :
tempProduct = (a[i] *
(presum[r[i]] -
presum[l[i] - 1 ]))
maxProduct = max (maxProduct,
tempProduct)
print (maxProduct)
if __name__ = = '__main__' :
n = 6
arr = [ 3 , 1 , 6 , 4 , 5 , 2 ]
maxValue(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG{
public static void maxValue( int [] a,
int n)
{
int [] presum = new int [n];
presum[0] = a[0];
for ( int i = 1; i < n; i++)
{
presum[i] = presum[i - 1] + a[i];
}
int [] l = new int [n], r = new int [n];
Stack< int > st = new Stack< int >();
for ( int i = 1; i < n; i++)
{
while (st.Count > 0 &&
a[st.Peek()] >= a[i])
st.Pop();
if (st.Count > 0)
l[i] = st.Peek() + 1;
else
l[i] = 0;
st.Push(i);
}
st.Clear();
for ( int i = n - 1; i >= 0; i--)
{
while (st.Count > 0 &&
a[st.Peek()] >= a[i])
st.Pop();
if (st.Count > 0)
r[i] = st.Peek() - 1;
else
r[i] = n - 1;
st.Push(i);
}
int maxProduct = 0;
int tempProduct;
for ( int i = 0; i < n; i++)
{
tempProduct = a[i] * (presum[r[i]] -
(l[i] == 0 ? 0 :
presum[l[i] - 1]));
maxProduct = Math.Max(maxProduct,
tempProduct);
}
Console.WriteLine(maxProduct);
}
static void Main()
{
int [] arr = { 3, 1, 6, 4, 5, 2 };
maxValue(arr, arr.Length);
}
}
|
Javascript
<script>
function maxValue(a, n)
{
var presum = Array(n);
presum[0] = a[0];
for ( var i = 1; i < n; i++)
{
presum[i] = presum[i - 1] + a[i];
}
var l = Array(n).fill(0), r = Array(n).fill(0);
var st = [];
for ( var i = 1; i < n; i++)
{
while (st.length!=0 &&
a[st[st.length-1]] >= a[i])
st.pop();
if (st.length!=0)
l[i] = st[st.length-1] + 1;
else
l[i] = 0;
st.push(i);
}
while (st.length!=0)
st.pop();
for ( var i = n - 1; i >= 0; i--)
{
while (st.length!=0 &&
a[st[st.length-1]] >= a[i])
st.pop();
if (st.length!=0)
r[i] = st[st.length-1] - 1;
else
r[i] = n - 1;
st.push(i);
}
var maxProduct = 0;
var tempProduct;
for ( var i = 0; i < n; i++)
{
tempProduct = a[i] * (presum[r[i]] -
(l[i] == 0 ? 0 :
presum[l[i] - 1]));
maxProduct = Math.max(maxProduct,
tempProduct);
}
document.write( maxProduct);
}
var n = 6;
var arr = [3, 1, 6, 4, 5, 2];
maxValue(arr, n);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Share your thoughts in the comments
Please Login to comment...