Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of minimum and maximum elements of all subarrays of size k.
Next article icon

Sum of (maximum element – minimum element) for all the subsets of an array.

Last Updated : 11 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[], the task is to compute the sum of (max{A} – min{A}) for every non-empty subset A of the array arr[].
Examples: 
 

Input: arr[] = { 4, 7 } 
Output: 3
There are three non-empty subsets: { 4 }, { 7 } and { 4, 7 }. 
max({4}) – min({4}) = 0 
max({7}) – min({7}) = 0 
max({4, 7}) – min({4, 7}) = 7 – 4 = 3.
Sum = 0 + 0 + 3 = 3
Input: arr[] = { 4, 3, 1 } 
Output: 9 
 

 

A naive solution is to generate all subsets and traverse every subset to find the maximum and minimum element and add their difference to the current sum. The time complexity of this solution is O(n * 2n).
An efficient solution is based on a simple observation stated below. 
 

For example, A = { 4, 3, 1 } 
Let value to be added in the sum for every subset be V.
Subsets with max, min and V values: 
{ 4 }, max = 4, min = 4 (V = 4 – 4) 
{ 3 }, max = 3, min = 3 (V = 3 – 3) 
{ 1 }, max = 1, min = 1 (V = 1 – 1) 
{ 4, 3 }, max = 4, min = 3 (V = 4 – 3) 
{ 4, 1 }, max = 4, min = 1 (V = 4 – 1) 
{ 3, 1 }, max = 3, min = 1 (V = 3 – 1) 
{ 4, 3, 1 }, max = 4, min = 1 (V = 4 – 1)
Sum of all V values 
= (4 – 4) + (3 – 3) + (1 – 1) + (4 – 3) + (4 – 1) + (3 – 1) + (4 – 1) 
= 0 + 0 + 0 + (4 – 3) + (4 – 1) + (3 – 1) + (4 – 1) 
= (4 – 3) + (4 – 1) + (3 – 1) + (4 – 1)
First 3 ‘V’ values can be ignored since they evaluate to 0 
(because they result from 1-sized subsets).
Rearranging the sum, we get:
= (4 – 3) + (4 – 1) + (3 – 1) + (4 – 1) 
= (1 * 0 – 1 * 3) + (3 * 1 – 3 * 1) + (4 * 3 – 4 * 0) 
= (1 * A – 1 * B) + (3 * C – 3 * D) + (4 * E – 4 * F)
where A = 0, B = 3, C = 1, D = 1, E = 3 and F = 0
If we closely look at the expression, instead of analyzing every subset, here we analyze every element of how many times it occurs as a minimum or a maximum element.
A = 0 implies that 1 doesn’t occur as a maximum element in any of the subsets. 
B = 3 implies that 1 occurs as a minimum element in 3 subsets. 
C = 1 implies that 3 occurs as a maximum element in 1 subset. 
D = 1 implies that 3 occurs as a minimum element in 1 subset. 
E = 3 implies that 4 occurs as a maximum element in 3 subsets. 
F = 0 implies that 4 doesn’t occur as a minimum element in any of the subsets.

If we somehow know the count of subsets for every element in which it occurs as a maximum element and a minimum element then we can solve the problem in linear time, since the computation above is linear in nature.
Let A = { 6, 3, 89, 21, 4, 2, 7, 9 } 
sorted(A) = { 2, 3, 4, 6, 7, 9, 21, 89 }
For example, we analyze element with value 6 (marked in bold). 3 elements are smaller than 6 and 4 elements are larger than 6. Therefore, if we think of all subsets in which 6 occurs with the 3 smaller elements, then in all those subsets 6 will be the maximum element. No of those subsets will be 23. Similar argument holds for 6 being the minimum element when it occurs with the 4 elements greater than 6. 
 

Hence, 
No of occurrences for an element as the maximum in all subsets = 2pos – 1 
No of occurrences for an element as the minimum in all subsets = 2n – 1 – pos – 1
where pos is the index of the element in the sorted array.

Below is the implementation of the above approach.
 

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
 
#define ll long long
 
using namespace std;
 
const int mod = 1000000007;
 
// Function to return a^n % mod
ll power(ll a, ll n)
{
    if (n == 0)
        return 1;
 
    ll p = power(a, n / 2) % mod;
    p = (p * p) % mod;
    if (n & 1) {
        p = (p * a) % mod;
    }
    return p;
}
 
// Compute sum of max(A) - min(A) for all subsets
ll computeSum(int* arr, int n)
{
 
    // Sort the array.
    sort(arr, arr + n);
 
    ll sum = 0;
    for (int i = 0; i < n; i++) {
 
        // Maxs = 2^i - 1
        ll maxs = (power(2, i) - 1 + mod) % mod;
        maxs = (maxs * arr[i]) % mod;
 
        // Mins = 2^(n-1-i) - 1
        ll mins = (power(2, n - 1 - i) - 1 + mod) % mod;
        mins = (mins * arr[i]) % mod;
 
        ll V = (maxs - mins + mod) % mod;
        sum = (sum + V) % mod;
    }
    return sum;
}
 
// Driver code
int main()
{
    int arr[] = { 4, 3, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << computeSum(arr, n);
    return 0;
}
 
 

Java




// Java implementation of the above approach
import java.util.*;
 
class GFG
{
 
static int mod = 1000000007;
 
    // Function to return a^n % mod
    static long power(long a, long n)
    {
        if (n == 0)
        {
            return 1;
        }
 
        long p = power(a, n / 2) % mod;
        p = (p * p) % mod;
        if (n == 1)
        {
            p = (p * a) % mod;
        }
        return p;
    }
 
    // Compute sum of max(A) - min(A) for all subsets
    static long computeSum(int[] arr, int n)
    {
 
        // Sort the array.
        Arrays.sort(arr);
 
        long sum = 0;
        for (int i = 0; i < n; i++)
        {
 
            // Maxs = 2^i - 1
            long maxs = (power(2, i) - 1 + mod) % mod;
            maxs = (maxs * arr[i]) % mod;
 
            // Mins = 2^(n-1-i) - 1
            long mins = (power(2, n - 1 - i) - 1 + mod) % mod;
            mins = (mins * arr[i]) % mod;
 
            long V = (maxs - mins + mod) % mod;
            sum = (sum + V) % mod;
        }
        return sum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = {4, 3, 1};
        int n = arr.length;
        System.out.println(computeSum(arr, n));
    }
}
 
// This code has been contributed by 29AjayKumar
 
 

Python3




# Python3 implementation of the
# above approach
 
# Function to return a^n % mod
def power(a, n):
 
    if n == 0:
        return 1
 
    p = power(a, n // 2) % mod
    p = (p * p) % mod
    if n & 1 == 1:
        p = (p * a) % mod
     
    return p
 
# Compute sum of max(A) - min(A)
# for all subsets
def computeSum(arr, n):
 
    # Sort the array.
    arr.sort()
 
    Sum = 0
    for i in range(0, n):
 
        # Maxs = 2^i - 1
        maxs = (power(2, i) - 1 + mod) % mod
        maxs = (maxs * arr[i]) % mod
 
        # Mins = 2^(n-1-i) - 1
        mins = (power(2, n - 1 - i) -
                      1 + mod) % mod
        mins = (mins * arr[i]) % mod
 
        V = (maxs - mins + mod) % mod
        Sum = (Sum + V) % mod
     
    return Sum
 
# Driver code
if __name__ =="__main__":
 
    mod = 1000000007
    arr = [4, 3, 1]
    n = len(arr)
 
    print(computeSum(arr, n))
 
# This code is contributed
# by Rituraj Jain
 
 

C#




// C# implementation of the above approach
using System;
using System.Collections;
 
class GFG
{
 
static int mod = 1000000007;
 
    // Function to return a^n % mod
    static long power(long a, long n)
    {
        if (n == 0)
        {
            return 1;
        }
 
        long p = power(a, n / 2) % mod;
        p = (p * p) % mod;
        if (n == 1)
        {
            p = (p * a) % mod;
        }
        return p;
    }
 
    // Compute sum of max(A) - min(A) for all subsets
    static long computeSum(int []arr, int n)
    {
 
        // Sort the array.
        Array.Sort(arr);
 
        long sum = 0;
        for (int i = 0; i < n; i++)
        {
 
            // Maxs = 2^i - 1
            long maxs = (power(2, i) - 1 + mod) % mod;
            maxs = (maxs * arr[i]) % mod;
 
            // Mins = 2^(n-1-i) - 1
            long mins = (power(2, n - 1 - i) - 1 + mod) % mod;
            mins = (mins * arr[i]) % mod;
 
            long V = (maxs - mins + mod) % mod;
            sum = (sum + V) % mod;
        }
        return sum;
    }
 
    // Driver code
    public static void Main()
    {
        int []arr = {4, 3, 1};
        int n = arr.Length;
        Console.WriteLine(computeSum(arr, n));
    }
}
 
// This code has been contributed by mits
 
 

PHP




<?php
// PHP implementation of the above approach
$mod = 1000000007;
 
// Function to return a^n % mod
function power($a, $n)
{
    global $mod;
    if ($n == 0)
        return 1;
 
    $p = power($a, $n / 2) % $mod;
    $p = ($p * $p) % $mod;
    if ($n & 1)
    {
        $p = ($p * $a) % $mod;
    }
    return $p;
}
 
// Compute sum of max(A) - min(A)
// for all subsets
function computeSum(&$arr, $n)
{
    global $mod;
     
    // Sort the array.
    sort($arr);
 
    $sum = 0;
    for ($i = 0; $i < $n; $i++)
    {
 
        // Maxs = 2^i - 1
        $maxs = (power(2, $i) - 1 + $mod) % $mod;
        $maxs = ($maxs * $arr[$i]) % $mod;
 
        // Mins = 2^(n-1-i) - 1
        $mins = (power(2, $n - 1 - $i) - 1 + $mod) % $mod;
        $mins = ($mins * $arr[$i]) % $mod;
 
        $V = ($maxs - $mins + $mod) % $mod;
        $sum = ($sum + $V) % $mod;
    }
    return $sum;
}
 
// Driver code
$arr = array( 4, 3, 1 );
$n = sizeof($arr);
 
echo computeSum($arr, $n);
 
// This code is contributed by ita_c
?>
 
 

Javascript




<script>
// Javascript implementation of the above approach
 
    let mod = 1000000007;
 
// Function to return a^n % mod
    function power(a,n)
    {
        if (n == 0)
        {
            return 1;
        }
   
        let p = power(a, n / 2) % mod;
        p = (p * p) % mod;
        if (n == 1)
        {
            p = (p * a) % mod;
        }
        return p;
    }
     
    // Compute sum of max(A) - min(A) for all subsets
    function computeSum(arr,n)
    {
        // Sort the array.
        arr.sort(function(a,b){return a-b;});
   
        let sum = 0;
        for (let i = 0; i < n; i++)
        {
   
            // Maxs = 2^i - 1
            let maxs = (power(2, i) - 1 + mod) % mod;
            maxs = (maxs * arr[i]) % mod;
   
            // Mins = 2^(n-1-i) - 1
            let mins = (power(2, n - 1 - i) - 1 + mod) % mod;
            mins = (mins * arr[i]) % mod;
   
            let V = (maxs - mins + mod) % mod;
            sum = (sum + V) % mod;
        }
        return sum;
    }
     
     // Driver code
    let arr=[4, 3, 1];
    let n = arr.length;
    document.write(computeSum(arr, n));
 
 
         
// This code is contributed by rag2127
</script>
 
 
Output: 
9

 

Time Complexity: O(N * log(N)) 
Auxiliary Space: O(1)



Next Article
Sum of minimum and maximum elements of all subarrays of size k.
author
rohan23chhabra
Improve
Article Tags :
  • Algorithms
  • Arrays
  • Combinatorial
  • Competitive Programming
  • Data Structures
  • DSA
  • Mathematical
  • subset
Practice Tags :
  • Algorithms
  • Arrays
  • Combinatorial
  • Data Structures
  • Mathematical
  • subset

Similar Reads

  • Find the minimum and maximum sum of N-1 elements of the array
    Given an unsorted array A of size N, the task is to find the minimum and maximum values that can be calculated by adding exactly N-1 elements. Examples: Input: a[] = {13, 5, 11, 9, 7} Output: 32 40 Explanation: Minimum sum is 5 + 7 + 9 + 11 = 32 and maximum sum is 7 + 9 + 11 + 13 = 40.Input: a[] = {
    10 min read
  • Split array into K subsets to maximize their sum of maximums and minimums
    Given an integer K and an array A[ ] whose length is multiple of K, the task is to split the elements of the given array into K subsets, each having an equal number of elements, such that the sum of the maximum and minimum elements of each subset is the maximum summation possible. Examples: Input: K
    6 min read
  • Sum of minimum and maximum elements of all subarrays of size k.
    Given an array of both positive and negative integers, the task is to compute sum of minimum and maximum elements of all sub-array of size k. Examples: Input : arr[] = {2, 5, -1, 7, -3, -1, -2} K = 4Output : 18Explanation : Subarrays of size 4 are : {2, 5, -1, 7}, min + max = -1 + 7 = 6 {5, -1, 7, -
    15+ min read
  • Maximum and minimum count of elements with sum at most K
    Given an array arr[] of size N and an integer K, the task is to find the maximum and minimum number of elements whose sum is less than equal to K. Examples: Input: N = 4, arr[ ] = {6, 2, 1, 3}, K = 7Output: 3 1Explanation:Maximum number of elements whose sum is less than equal to K is 3 i.e [1, 2, 3
    7 min read
  • Sum of maximum elements of all subsets
    Given an array of integer numbers, we need to find sum of maximum number of all possible subsets. Examples: Input : arr = {3, 2, 5}Output : 28Explanation : Subsets and their maximum are,{} maximum = 0{3} maximum = 3{2} maximum = 2{5} maximum = 5{3, 2} maximum = 3{3, 5} maximum = 5{2, 5} maximum = 5{
    9 min read
  • Minimum value among AND of elements of every subset of an array
    Given an array of integers, the task is to find the AND of all elements of each subset of the array and print the minimum AND value among all those.Examples: Input: arr[] = {1, 2, 3} Output: 0 AND of all possible subsets (1 & 2) = 0, (1 & 3) = 1, (2 & 3) = 2 and (1 & 2 & 3) = 0.
    3 min read
  • Maximum and minimum sum of Bitwise XOR of pairs from an array
    Given an array arr[] of size N, the task is to find the maximum and minimum sum of Bitwise XOR of all pairs from an array by splitting the array into N / 2 pairs. Examples: Input: arr[] = {1, 2, 3, 4}Output: 6 10Explanation:Bitwise XOR of the all possible pair splits are as follows:(1, 2), (3, 4) →
    11 min read
  • Maximize the minimum element of Array by reducing elements one by one
    Given an array arr[] containing N integers. In each operation, a minimum integer is chosen from the array and deleted from the array after subtracting it from the remaining elements. The task is to find the maximum of minimum values of the array after any number of such operations. Examples: Input:
    6 min read
  • Remove all occurrences of any element for maximum array sum
    Given an array of positive integers, remove all the occurrences of the element to get the maximum sum of the remaining array. Examples: Input : arr = {1, 1, 3} Output : 3 On removing 1 from the array, we get {3}. The total value is 3 Input : arr = {1, 1, 3, 3, 2, 2, 1, 1, 1} Output : 11 On removing
    6 min read
  • Distribute given arrays into K sets such that total sum of maximum and minimum elements of all sets is maximum
    Given two arrays, the first arr[] of size N and the second brr[] of size K. The task is to divide the first array arr[] into K sets such that the i-th set should contain brr[i] elements from the second array brr[], and the total sum of maximum and minimum elements of all sets is maximum. Examples: I
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences