Sum of ( maximum element | Javascript 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
let mod = 1000000007 ; 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 ; } function computeSum ( arr , n ) { arr . sort ( function ( a , b ) { return a - b ; } ) ; let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { let maxs = ( power ( 2 , i ) - 1 + mod ) % mod ; maxs = ( maxs * arr [ i ] ) % mod ; 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 ; } let arr = [ 4 , 3 , 1 ] ; let n = arr . length ; document . write ( computeSum ( arr , n ) ) ;