Program to find sum of absolute differences in a sorted array in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums and that is sorted in non-decreasing order. We have to make an array called result with the same length as nums such that result[i] is the summation of absolute differences between nums[i] and all the other elements in the array.

So, if the input is like nums = [5,7,12], then the output will be [9, 7, 12] because

  • |5-5| + |5-7| + |5-12| = 0+2+7 = 9
  • |7-5| + |7-7| + |7-12| = 2+0+5 = 7
  • |5-12| + |7-12| + |12-12| = 7+5+0 = 12

To solve this, we will follow these steps −

  • res := a new list
  • s:= 0
  • n := size of nums
  • for i in range 1 to n - 1, do
    • s := s + nums[i] - nums[0]
  • insert s at the end of res
  • for i in range 1 to n - 1, do
    • diff := nums[i] - nums[i-1]
    • s := s + diff*i
    • s := s - diff *(n-i)
  • insert s at the end of res
  • return res

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   res = []
   s=0
   n = len(nums)
   for i in range(1,n):
      s+=nums[i]-nums[0]
   res.append(s)
   for i in range(1,n):
      diff = nums[i]-nums[i-1]
      s += diff*i
      s -= diff *(n-i)
      res.append(s)
   return res

nums = [5,7,12]
print(solve(nums))

Input

[5,7,12]

Output

[9, 7, 12]
raja
Updated on 06-Oct-2021 10:55:36

Advertisements