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 .
ans = 0 NEW_LINE pre_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += ( i * a [ i ] ) - pre_sum NEW_LINE pre_sum += a [ i ] NEW_LINE DEDENT