Sum of width ( max and min diff ) of all Subsequences | Java implementation of above approach ; Function to return sum of width of all subsets ; Sort the array ; Driver program
import java . util . Arrays ; class GFG { static int MOD = 1000000007 ; static int SubseqWidths ( int [ ] A , int n ) { Arrays . sort ( A ) ; int [ ] pow2 = new int [ 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 ; } public static void main ( String [ ] args ) { int [ ] A = new int [ ] { 5 , 6 , 4 , 3 , 8 } ; int n = A . length ; System . out . println ( SubseqWidths ( A , n ) ) ; } }