Traverse in the list from start to end number of times a [ i ] can be in a pair and to get the difference we subtract pre_sum .
int ans = 0 , pre_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans += ( i * a [ i ] ) - pre_sum ; pre_sum += a [ i ] ;