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