Find the sum of maximum difference possible from all subset of a given array. - GeeksforGeeks

18 Nov, 2021
We are given an array arr[] of n non-negative integers (repeated elements allowed), find out the sum of maximum difference possible from all subsets of the given array. Suppose max(s) represents the maximum value in any subset ‘s’ whereas min(s) represents the minimum value in the set ‘s’. We need to find the sum of max(s)-min(s) for all possible subsets. 
Examples: 
Input : arr[] = {1, 2, 3}
Output : result = 6

Explanation : 
All possible subset and for each subset s,
max(s)-min(s) are as :
SUBSET    |  max(s) | min(s) | max(s)-min(s)
{1, 2}    |  2      |  1     |   1
{1, 3}    |  3      |  1     |   2
{2, 3}    |  3      |  2     |   1
{1, 2, 3} |  3      |  1     |   2
Total Difference sum = 6
Note : max(s) - min(s) for all subset with 
single element must be zero.

Input : arr[] = {1, 2, 2}
Output : result = 3

Explanation : 
All possible subset and for each subset s,
max(s)-min(s) are as :
  SUBSET  |  max(s) | min(s)| max(s)-min(s)
  {1, 2}  |  2      |  1    |   1
  {1, 2}  |  2      |  1    |   1
  {2, 2}  |  2      |  2    |   0
{1, 2, 2} |  2      |  1    |   1
Total Difference sum = 3
Basic Approach: Compute the sum of the maximum element of each subset, and the sum of the minimum element of each subset separately, and then subtract the minimum sum from the maximum to get the answer. The sum of the maximum/ minimum element of each subset can be computed easily by iterating through the elements of each subset. But as we have to iterate through all subsets the time complexity for this approach is exponential O(n2^n).Efficient Approach: As we have to compute the sum of the maximum element of each subset, and the sum of the minimum element of each subset separately here is an efficient way to perform this calculation. Sum of Minimum Elements of All Subsets: Let us say that the elements of arr[] in non-decreasing order are {a1,a2,..., an}. Now, we can partition the subsets of arr[] into the following categories:  
Subsets containing element a1: These subsets can be obtained by taking any subset of {a2,a3,..., an} and then adding a1 into it. The number of such subsets will be 2n-1, and they all have a1 as their minimum element.
Subsets not containing element a1, but containing a2: These subsets can be obtained by taking any subset of {a3, a4,...,an}, and then adding a2 into it. The number of such subsets will be 2n-2, and they all have a2 as their minimum element.
.....
Subsets not containing elements a1, a2,..., ai-1 but containing ai: These subsets can be obtained by taking any subset of {ai+1,ai+2,..., an}, and then adding ai into it. The number of such subsets will be 2n-i, and they all have ai as their minimum element.
it can be seen that the above iteration is complete, i.e., it considers each subset exactly once. Hence, the sum of the minimum element of all subsets will be:min_sum = a1*2n-1 + a2*2n-2 + ... + an*20 This sum can be computed easily in linear time with help of the Horner method...Similarly, we can compute the sum of the maximum element of all subsets of arr[]. The only difference is that we need to iterate the elements of arr[] in non-increasing order. Note: We may have a large answer, so we have to calculate the answer with mod 10^9 +7. 
C++
Java
Python3
C#
PHP
Javascript
// CPP for finding max min difference// from all subset of given set#include <bits/stdc++.h>using namespace std;  const long long int MOD = 1000000007;  // function for sum of max min difference int maxMin (int arr[], int n) {    // sort all numbers    sort(arr, arr + n);          // iterate over array and with help of     // horner's rule calc max_sum and min_sum    long long int min_sum = 0, max_sum = 0;    for (int i = 0; i < n; i++)    {        max_sum = 2 * max_sum + arr[n-1-i];        max_sum %= MOD;        min_sum = 2 * min_sum + arr[i];        min_sum %= MOD;    }      return (max_sum - min_sum + MOD) % MOD;}  // Driver Codeint main(){    int arr[] = {1, 2, 3, 4};    int n = sizeof(arr) / sizeof(arr[0]);    cout << maxMin(arr,n);    return 0;} 
// JAVA Code for Find the sum of maximum // difference possible from all subset // of a given array.import java.util.*;  class GFG {          public static int MOD = 1000000007;          // function for sum of max min difference     public static long maxMin (int arr[], int n)     {        // sort all numbers        Arrays.sort(arr);                  // iterate over array and with help of         // horner's rule calc max_sum and min_sum        long min_sum = 0, max_sum = 0;        for (int i = 0; i < n; i++)        {            max_sum = 2 * max_sum + arr[n - 1 - i];            max_sum %= MOD;            min_sum = 2 * min_sum + arr[i];            min_sum %= MOD;        }              return (max_sum - min_sum + MOD)%MOD;    }          // Driver Code    public static void main(String[] args)     {            int arr[] = {1, 2, 3, 4};            int n = arr.length;            System.out.println(maxMin(arr, n));    }}  // This code is contributed by Arnav Kr. Mandal.
# python for finding max min difference#from all subset of given set  MOD = 1000000007;  # function for sum of max min difference def maxMin (arr,n):          # sort all numbers    arr.sort()          # iterate over array and with help of     # horner's rule calc max_sum and min_sum    min_sum = 0    max_sum = 0    for i in range(0,n):                  max_sum = 2 * max_sum + arr[n-1-i];        max_sum %= MOD;        min_sum = 2 * min_sum + arr[i];        min_sum %= MOD;          return (max_sum - min_sum + MOD) % MOD;  # Driver Codearr = [1, 2, 3, 4]n = len(arr)print( maxMin(arr, n))  # This code is contributed by Sam007.
   // C# Code to Find the sum of maximum // difference possible from all subset // of a given array.using System;  class GFG {          public static int MOD = 1000000007;          // function for sum of max min difference     public static long maxMin (int []arr, int n)     {        // sort all numbers        Array.Sort(arr);                  // iterate over array and with help of         // horner's rule calc max_sum and min_sum        long min_sum = 0, max_sum = 0;        for (int i = 0; i < n; i++)        {            max_sum = 2 * max_sum + arr[n - 1 - i];            max_sum %= MOD;            min_sum = 2 * min_sum + arr[i];            min_sum %= MOD;        }              return (max_sum - min_sum + MOD) % MOD;    }          // Driver Code    public static void Main()     {            int []arr = {1, 2, 3, 4};            int n = arr.Length;            Console.Write(maxMin(arr, n));        }}  // This code is contributed by nitin mittal
<?php// PHP for finding max min difference// from all subset of given set$MOD = 1000000007;  // function for sum of // max min difference function maxMin ($arr, $n) {    global $MOD;          // sort all numbers    sort($arr);          // iterate over array     // and with help of     // horner's rule calc     // max_sum and min_sum    $min_sum = 0; $max_sum = 0;          for ($i = 0; $i < $n;$i++)    {        $max_sum = 2 * $max_sum +                        $arr[$n - 1 - $i];        $max_sum %= $MOD;        $min_sum = 2 * $min_sum + $arr[$i];        $min_sum %= $MOD;    }      return ($max_sum - $min_sum + $MOD) % $MOD;}  // Driver Code$arr = array(1, 2, 3, 4);$n = count($arr);echo maxMin($arr, $n);  // This code is contributed by vt_m. ?>
<script>  // Javascript for finding max min difference// from all subset of given set  var MOD = 1000000007;  // function for sum of max min difference function maxMin (arr, n) {    // sort all numbers    arr.sort((a,b)=> a-b);          // iterate over array and with help of     // horner's rule calc max_sum and min_sum    var min_sum = 0, max_sum = 0;    for (var i = 0; i < n; i++)    {        max_sum = 2 * max_sum + arr[n-1-i];        max_sum %= MOD;        min_sum = 2 * min_sum + arr[i];        min_sum %= MOD;    }      return (max_sum - min_sum + MOD) % MOD;}  // Driver Codevar arr = [1, 2, 3, 4];var n = arr.length;document.write( maxMin(arr,n));  </script>
Output:
23
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
vt_m
Sam007
987saurabhpatel
itsok
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Queue | Set 1 (Introduction and Array Implementation)