Given an array arr[] consisting of N positive integers, the task is to find the product of the maximum of all possible subsets of the given array. Since the product can be very large, print it to modulo (109 + 7).
Examples:
Input: arr[] = {1, 2, 3}
Output:
Explanation:
All possible subsets of the given array with their respective maximum elements are:
- {1}, the maximum element is 1.
- {2}, the maximum element is 2.
- {3}, the maximum element is 3.
- {1, 2}, the maximum element is 2.
- {1, 3}, the maximum element is 3.
- {2, 3}, the maximum element is 3.
- {1, 2, 3}, the maximum element is 3.
The product of all the above maximum element is 1*2*3*2*3*3*3 = 324.
Input: arr[] = {1, 1, 1, 1}
Output: 1
Naive Approach: The simplest approach to solve the given problem is to generate all possible subsets of the given array and find the product of the maximum of all the generated subsets modulo (109 + 7) as the resultant product.
C++
| // C++ code for the approach  #include <bits/stdc++.h>usingnamespacestd;  #define mod 1000000007  // Function to find the product of the maximum of all// possible subsetslonglongintmaxProduct(intarr[], intn) {    longlongintans = 1;      // Generate all possible subsets of the array    for(inti = 0; i < (1 << n); i++) {        longlongintmaxVal = INT_MIN;          // Find the maximum value of each subset        for(intj = 0; j < n; j++) {            if((i & (1 << j)) != 0) {                maxVal = max(maxVal, (longlongint)arr[j]);            }        }          // Multiply the maximum value of each subset to the        // answer        if(maxVal != INT_MIN)            ans = (ans * maxVal) % mod;    }      returnans;}  // Function to print the product of the maximum of all// possible subsets of the arrayvoidprintMaxProduct(intarr[], intn) {    longlongintans = maxProduct(arr, n);    cout << ans << endl;}  // Driver codeintmain() {    // Input array    intarr[] = { 1, 2, 3 };    // Size of the array    intn = sizeof(arr) / sizeof(arr[0]);      // Print the product of the maximum of all    // possible subsets of the array    printMaxProduct(arr, n);      return0;} | 
Java
| // Java program for the above approachimportjava.util.*;  publicclassMain {    staticfinalintmod = 1000000007;      // Function to find the product of    // the maximum of all possible subsets    staticlongmaxProduct(int[] arr, intn)    {        longans = 1;          // Generate all possible subsets        // of the array        for(inti = 0; i < (1<< n); i++) {            longmaxVal = Integer.MIN_VALUE;              // Find the maximum value of            // each subset            for(intj = 0; j < n; j++) {                if((i & (1<< j)) != 0) {                    maxVal = Math.max(maxVal, arr[j]);                }            }              // Multiply the maximum value of            // each subset to the answer            if(maxVal != Integer.MIN_VALUE) {                ans = (ans * maxVal) % mod;            }        }          returnans;    }      // Function to print the product of the    // maximum of all possible subsets    // of the array    staticvoidprintMaxProduct(int[] arr, intn)    {        longans = maxProduct(arr, n);        System.out.println(ans);    }      // Driver code    publicstaticvoidmain(String[] args)    {        // Input array        int[] arr = { 1, 2, 3};        // Size of the array        intn = arr.length;          // Print the product of the maximum of all        // possible subsets of the array        printMaxProduct(arr, n);    }} | 
Python3
| # Python3 code for the approachMOD =int(1e9+7)  # Function to find the product of the maximum of all# possible subsetsdefmaxProduct(arr, n):  ans =1  Â  # Generate all possible subsets of the array  fori inrange(1<< n):    maxVal =float('-inf')    Â    # Find the maximum value of each subset    forj inrange(n):      ifi & (1<< j):        maxVal =max(maxVal, arr[j])       Â    # Multiply the maximum value of each subset to the    # answer    ifmaxVal !=float('-inf'):      ans =(ans *maxVal) %MOD          Â          Â  returnans  # Function to print the product of the maximum of all# possible subsets of the arraydefprintMaxProduct(arr, n):    ans =maxProduct(arr, n)    print(ans)  Â# Driver codeif__name__ =='__main__':    # Input array    arr =[1, 2, 3]    # Size of the array    n =len(arr)    Â    # Print the product of the maximum of all    # possible subsets of the array    printMaxProduct(arr, n) | 
C#
| usingSystem;  publicclassGFG {  staticreadonlyintmod = 1000000007;    // Function to find the product of  // the maximum of all possible subsets  staticlongMaxProduct(int[] arr, intn)  {    longans = 1;      // Generate all possible subsets    // of the array    for(inti = 0; i < (1 << n); i++) {      longmaxVal = int.MinValue;        // Find the maximum value of      // each subset      for(intj = 0; j < n; j++) {        if((i & (1 << j)) != 0) {          maxVal = Math.Max(maxVal, arr[j]);        }      }        // Multiply the maximum value of      // each subset to the answer      if(maxVal != int.MinValue) {        ans = (ans * maxVal) % mod;      }    }      returnans;  }    // Function to print the product of the  // maximum of all possible subsets  // of the array  staticvoidPrintMaxProduct(int[] arr, intn)  {    longans = MaxProduct(arr, n);    Console.WriteLine(ans);  }    // Driver code  publicstaticvoidMain()  {    // Input array    int[] arr = { 1, 2, 3 };    // Size of the array    intn = arr.Length;      // Print the product of the maximum of all    // possible subsets of the array    PrintMaxProduct(arr, n);  }}  //This code is contributed by aeroabrar_31 | 
Javascript
| // JavaScript code to find the product of the maximum of all possible subsets  const mod = 1000000007;  functionmaxProduct(arr, n) {    let ans = 1;      // Generate all possible subsets of the array    for(let i = 0; i < (1 << n); i++) {        let maxVal = Number.MIN_SAFE_INTEGER;          // Find the maximum value of each subset        for(let j = 0; j < n; j++) {            if((i & (1 << j)) !== 0) {                maxVal = Math.max(maxVal, arr[j]);            }        }          // Multiply the maximum value of each subset to the answer        if(maxVal !== Number.MIN_SAFE_INTEGER) {            ans = (ans * maxVal) % mod;        }    }      returnans;}  functionprintMaxProduct(arr, n) {    let ans = maxProduct(arr, n);    console.log(ans);}  // Driver codelet arr = [1, 2, 3];let n = arr.length;  // Print the product of the maximum of all possible subsets of the arrayprintMaxProduct(arr, n); | 
324
Time Complexity: O(N*2N)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized based on the following observations:
- The idea is to count the number of times each array element occurs as the maximum element among all possible subsets formed.
- An array element arr[i] is a maximum if and only if all the elements except arr[i] are smaller than or equal to it.
- Therefore, the number of subsets formed by all elements smaller than or equal to each array element arr[i] contributes to the count of subsets having arr[i] as the maximum element.
Follow the steps below to solve the problem:
- Initialize a variable, say maximumProduct as 1 that stores the resultant product of maximum elements of all subsets.
- Sort the given array arr[] in the increasing order.
- Traverse the array from the end using the variable i and perform the following steps:
- Find the number of subsets that are smaller than the current element arr[i] as (2i – 1) and store it in a variable say P.
- Since the array element arr[i] contributes P number of times, therefore multiply the value arr[i], P times to the variable maximumProduct.
 
- Find the product of the array element with maximumProduct for including all the subsets of size 1.
- After completing the above steps, print the value of maximumProduct as the resultant maximum product.
Below is the implementation of the above approach:
C++
| // C++ program for the above approach  #include <bits/stdc++.h>usingnamespacestd;  // Function to find the product of the// maximum of all possible subsetslongmaximumProduct(intarr[], intN){    longmod = 1000000007;      // Sort the given array arr[]    sort(arr, arr + N);      // Stores the power of 2    longpower[N + 1];    power[0] = 1;      // Calculate the power of 2    for(inti = 1; i <= N; i++) {        power[i] = 2 * power[i - 1];        power[i] %= mod;    }      // Stores the resultant product    longresult = 1;      // Traverse the array from the back    for(inti = N - 1; i > 0; i--) {          // Find the value of 2^i - 1        longvalue = (power[i] - 1);          // Iterate value number of times        for(intj = 0; j < value; j++) {              // Multiply value with            // the result            result *= 1LL * arr[i];            result %= mod;        }    }      // Calculate the product of array    // elements with result to consider    // the subset of size 1    for(inti = 0; i < N; i++) {        result *= 1LL * arr[i];        result %= mod;    }      // Return the resultant product    returnresult;}  // Driver Codeintmain(){      intarr[] = { 1, 2, 3 };    intN = sizeof(arr) / sizeof(arr[0]);    cout << maximumProduct(arr, N);      return0;} | 
Java
| // Java program for the above approachimportjava.util.Arrays;  classGFG{  // Function to find the product of the// maximum of all possible subsetsstaticlongmaximumProduct(intarr[], intN){    longmod = 1000000007;      // Sort the given array arr[]    Arrays.sort(arr);      // Stores the power of 2    longpower[] = newlong[N + 1];    power[0] = 1;      // Calculate the power of 2    for(inti = 1; i <= N; i++)     {        power[i] = 2* power[i - 1];        power[i] %= mod;    }      // Stores the resultant product    longresult = 1;      // Traverse the array from the back    for(inti = N - 1; i > 0; i--)     {        Â        // Find the value of 2^i - 1        longvalue = (power[i] - 1);          // Iterate value number of times        for(intj = 0; j < value; j++)         {            Â            // Multiply value with            // the result            result *= arr[i];            result %= mod;        }    }      // Calculate the product of array    // elements with result to consider    // the subset of size 1    for(inti = 0; i < N; i++)    {        result *= arr[i];        result %= mod;    }      // Return the resultant product    returnresult;}  // Driver Codepublicstaticvoidmain(String[] args){    intarr[] = { 1, 2, 3};    intN = arr.length;    Â    System.out.println(maximumProduct(arr, N));}}  // This code is contributed by rishavmahato348 | 
Python3
| # Python3 program for the above approach  # Function to find the product of the# maximum of all possible subsetsdefmaximumProduct(arr, N):    Â    mod =1000000007      # Sort the given array arr[]    arr =sorted(arr)      # Stores the power of 2    power =[0] *(N +1)    power[0] =1      # Calculate the power of 2    fori inrange(1, N +1):        power[i] =2*power[i -1]        power[i] %=mod      # Stores the resultant product    result =1      # Traverse the array from the back    fori inrange(N -1, -1, -1):        Â        # Find the value of 2^i - 1        value =(power[i] -1)          # Iterate value number of times        forj inrange(value):            Â            # Multiply value with            # the result            result *=arr[i]            result %=mod      # Calculate the product of array    # elements with result to consider    # the subset of size 1    fori inrange(N):        result *=arr[i]        result %=mod        Â    # Return the resultant product    returnresult  # Driver Codeif__name__ =='__main__':    Â    arr =[ 1, 2, 3]    N =len(arr)    Â    print(maximumProduct(arr, N))  # This code is contributed by mohit kumar 29 | 
C#
| // C# program for the above approachusingSystem;usingSystem.Collections.Generic;  classGFG{  // Function to find the product of the// maximum of all possible subsetsstaticlongmaximumProduct(int[]arr, intN){    longmod = 1000000007;      // Sort the given array arr[]    Array.Sort(arr);      // Stores the power of 2    long[]power = newlong[N + 1];    power[0] = 1;      // Calculate the power of 2    for(inti = 1; i <= N; i++) {        power[i] = 2 * power[i - 1];        power[i] %= mod;    }      // Stores the resultant product    longresult = 1;      // Traverse the array from the back    for(inti = N - 1; i > 0; i--) {          // Find the value of 2^i - 1        longvalue = (power[i] - 1);          // Iterate value number of times        for(intj = 0; j < value; j++) {              // Multiply value with            // the result            result *= 1 * arr[i];            result %= mod;        }    }      // Calculate the product of array    // elements with result to consider    // the subset of size 1    for(inti = 0; i < N; i++) {        result *= 1 * arr[i];        result %= mod;    }      // Return the resultant product    returnresult;}  // Driver CodepublicstaticvoidMain(){      int[]arr = {1, 2, 3};    intN = arr.Length;    Console.Write(maximumProduct(arr, N));}}  // This code is contributed by SURENDRA_GANGWAR. | 
Javascript
| <script>  // JavaScript program for the above approach    // Function to find the product of the// maximum of all possible subsetsfunctionmaximumProduct(arr, N){    let mod = 1000000007;      // Sort the given array arr[]    arr.sort((a, b) =>  a - b);      // Stores the power of 2    let power = newArray(N + 1);    power[0] = 1;      // Calculate the power of 2    for(let i = 1; i <= N; i++) {        power[i] = 2 * power[i - 1];        power[i] %= mod;    }      // Stores the resultant product    let result = 1;      // Traverse the array from the back    for(let i = N - 1; i > 0; i--) {          // Find the value of 2^i - 1        let value = (power[i] - 1);          // Iterate value number of times        for(let j = 0; j < value; j++) {              // Multiply value with            // the result            result *= 1 * arr[i];            result %= mod;        }    }      // Calculate the product of array    // elements with result to consider    // the subset of size 1    for(let i = 0; i < N; i++) {        result *= 1 * arr[i];        result %= mod;    }      // Return the resultant product    returnresult;}  // Driver Code  let arr = [1, 2, 3 ];let N = arr.length;document.write(maximumProduct(arr, N));  </script> | 
324
Â
Time Complexity: O(N*
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







