Program to find the sum of the absolute differences of every pair in a sorted list in Python

ProgrammingPythonServer Side Programming

Suppose we have a list of sorted numbers called nums, we have to find the sum of the absolute differences between every pair of numbers in the given list. Here we will consider (i, j) and (j, i) are different pairs. If the answer is very large, mod the result by 10^9+7.

So, if the input is like nums = [2, 4, 8], then the output will be 24, as |2 - 4| + |2 - 8| + |4 - 2| + |4 - 8| + |8 - 2| + |8 - 4|.

To solve this, we will follow these steps −

  • m = 10^9 + 7

  • total := 0

  • for i in range 0 to size of nums, do

    • total := total +(i*nums[i] - (size of nums - 1 - i) *nums[i]) mod m

  • return (2*total) mod m

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      m = 10**9 + 7
      total = 0
      for i in range(len(nums)):
         total += (i*nums[i] - (len(nums) - 1 - i)*nums[i]) % m
      return (2*total) % m
ob = Solution()
nums = [2, 4, 8]
print(ob.solve(nums))

Input

[2, 4, 8]

Output

24
raja
Published on 07-Oct-2020 14:28:46
Advertisements