human
Sum of f ( a [ i ] , a [ j ] ) over all pairs in an array of n integers | Function to calculate the sum.
map to keep a count of occurrences.
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 ..
if the ( a [ i ] - 1 ) is present then subtract that value as f ( a [ i ] , a [ i ] - 1 ) = 0.
if the ( a [ i ] + 1 ) is present then add that value as f ( a [ i ] , a [ i ] - 1 ) = 0 here we add as a [ i ] - ( a [ i ] - 1 ) < 0 which would have been added as negative sum , so we add to remove this pair from the sum value.
keeping a counter for every element.
Driver Code"
Solution in Python:
 Write me a code to sum of f ( a [ i ] , a [ j ] ) over all pairs in an array of n integers and the other steps required?
assistant
#Here is code to sum of f ( a [ i ] , a [ j ] ) over all pairs in an array of n integers and the other steps required.
 def sum ( a , n ) :
	cnt = dict ( )
	ans = 0
	pre_sum = 0
	for i in range ( n ) :
		ans += ( i * a [ i ] ) - pre_sum
		pre_sum += a [ i ]
		if ( a [ i ] - 1 ) in cnt :
			ans -= cnt [ a [ i ] - 1 ]
		if ( a [ i ] + 1 ) in cnt :
			ans += cnt [ a [ i ] + 1 ]
		if a [ i ] not in cnt :
			cnt [ a [ i ] ] = 0
		cnt [ a [ i ] ] += 1
	return ans
if __name__ == ' _ _ main _ _ ' :
	a = [ 1 , 2 , 3 , 1 , 3 ]
	n = len ( a )
	print ( sum ( a , n ) )