Minimum product of maximum and minimum element over all possible subarrays
Last Updated :
20 Mar, 2023
Given an array arr[] consisting of N positive integers, the task is to find the minimum product of maximum and minimum among all possible subarrays.
Examples:
Input: arr[] = {6, 4, 5, 6, 2, 4}
Output: 8
Explanation:
Consider the subarray {2, 4}, the product of minimum and maximum for this subarray is 2*4 = 8, which is minimum among all possible subarrays.
Input: arr[] = {3, 1, 5, 2, 3, 2}
Output: 3
Naive Approach: The simplest approach to solve the given problem is to generate all possible subarrays of the array and find the product of the maximum and minimum of all possible subarrays. After checking for all the subarrays print the minimum of all products obtained.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimize by using an observation that considering the pair of adjacent elements as an subarray because including any array element may increase our maximum element which result in the maximum product.
Therefore, the idea is to find the minimum of product of all pair of adjacent elements to find the resultant minimum product.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findMinMax(vector< int >& a)
{
int min_val = 1000000000;
for ( int i = 1; i < a.size(); ++i) {
min_val = min(min_val, a[i] * a[i - 1]);
}
return min_val;
}
int main()
{
vector< int > arr = { 6, 4, 5, 6, 2, 4, 1 };
cout << findMinMax(arr);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int findMinMax( int [] a)
{
int min_val = 1000000000 ;
for ( int i = 1 ; i < a.length; ++i) {
min_val = Math.min(min_val, a[i] * a[i - 1 ]);
}
return min_val;
}
public static void main (String[] args)
{
int [] arr = { 6 , 4 , 5 , 6 , 2 , 4 , 1 };
System.out.println(findMinMax(arr));
}
}
|
Python3
def findMinMax(a):
min_val = 1000000000
for i in range ( 1 , len (a)):
min_val = min (min_val, a[i] * a[i - 1 ])
return min_val
if __name__ = = ( "__main__" ):
arr = [ 6 , 4 , 5 , 6 , 2 , 4 , 1 ]
print (findMinMax(arr))
|
C#
using System;
public class GFG
{
static int findMinMax( int [] a)
{
int min_val = 1000000000;
for ( int i = 1; i < a.Length; ++i) {
min_val = Math.Min(min_val, a[i] * a[i - 1]);
}
return min_val;
}
public static void Main ( string [] args)
{
int [] arr = { 6, 4, 5, 6, 2, 4, 1 };
Console.WriteLine(findMinMax(arr));
}
}
|
Javascript
<script>
function findMinMax( a)
{
let min_val = 1000000000;
for (let i = 1; i < a.length; ++i) {
min_val = Math.min(min_val, a[i] * a[i - 1]);
}
return min_val;
}
let arr = [6, 4, 5, 6, 2, 4, 1];
document.write( findMinMax(arr))
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...