Program to find minimum absolute sum difference in Python

PythonServer Side ProgrammingProgramming

Suppose we have two positive valued arrays nums1 and nums2, of same size. The absolute sum difference of these two arrays is the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). Now, we can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. We have to find the minimum absolute sum difference after replacing at most one element in the array nums1. The answer may be very large so return it modulo 10^9 + 7.

So, if the input is like nums1 = [2,8,6], nums2 = [3,4,6], then the output will be 3 because, we can find two possible optimal solutions

  • Replace the element at index 1 with the element at index 0: [2,8,6] => [2,2,6], or

  • Replace the element at index 1 with the element at index 2: [2,8,6] => [2,6,6].

Both of them get a sum difference of |2-3| + (|2-4| or |6-4|) + |6-6| = 3.

To solve this, we will follow these steps −

  • if nums1 is same as nums2, then

    • return(0)

  • minn_diff := -infinity

  • ind := -1

  • for i in range 0 to size of nums1 - 1, do

    • if |nums1[i]-nums2[i]| > minn_diff, then

      • ind := i

      • minn_diff := |nums1[i] - nums2[i]|

  • diff := |nums1[ind] - nums2[ind]|

  • index := ind

  • for i in range 0 to size of nums1 - 1, do

    • if i is not same as ind, then

      • if |nums1[i] - nums2[ind]| < diff, then

        • index := i

        • diff := |nums1[i]-nums2[ind]|

  • summ := 0

  • for i in range 0 to size of nums1 - 1, do

    • if i is same as ind, then

      • summ := summ + |nums1[index] - nums2[i]|

    • otherwise,

      • summ := summ + |nums1[i] - nums2[i]|

  • return summ mod (10^9 + 7)

Example

Let us see the following implementation to get better understanding −

def solve(nums1, nums2):
   if(nums1==nums2):
      return(0)

   minn_diff = float('-inf')
   ind = -1
   for i in range(len(nums1)):
      if(abs(nums1[i]-nums2[i]) > minn_diff):
         ind = i
         minn_diff = abs(nums1[i]-nums2[i])
   
   diff = abs(nums1[ind]-nums2[ind])
   index = ind
   for i in range(len(nums1)):
      if(i!=ind):
         if(abs(nums1[i]-nums2[ind])<diff):
            index = i
            diff = abs(nums1[i]-nums2[ind])

   summ = 0
   for i in range(len(nums1)):
      if(i==ind):
         summ += abs(nums1[index]-nums2[i])
      else:
         summ += abs(nums1[i]-nums2[i])
   return(summ%(10**9 + 7))

nums1 = [2,8,6]
nums2 = [3,4,6]
print(solve(nums1, nums2))

Input

[2,8,6], [3,4,6]

Output

3
raja
Published on 07-Oct-2021 12:51:40
Advertisements