Sum of width ( max and min diff ) of all Subsequences | CPP implementation of above approach ; Function to return sum of width of all subsets ; Sort the array ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD  1000000007 NEW_LINE int SubseqWidths ( int A [ ] , int n ) { sort ( A , A + n ) ; int pow2 [ n ] ; pow2 [ 0 ] = 1 ; for ( int i = 1 ; i < n ; ++ i ) pow2 [ i ] = ( pow2 [ i - 1 ] * 2 ) % MOD ; int ans = 0 ; for ( int i = 0 ; i < n ; ++ i ) ans = ( ans + ( pow2 [ i ] - pow2 [ n - 1 - i ] ) * A [ i ] ) % MOD ; return ans ; } int main ( ) { int A [ ] = { 5 , 6 , 4 , 3 , 8 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << SubseqWidths ( A , n ) ; return 0 ; }