Program to find minimum operations needed to make two arrays sum equal in Python



Suppose we have two lists nums1 and nums2 where each element in both of the lists in range 1 to 6. Now consider an operation by which, we can select a number from nums1 or nums2 and update its value to a number between 1 to 6. We have to find the minimum number of operations needed so that the sum of these two arrays are same. If we cannot find any solution, return -1.

So, if the input is like nums1 = [1, 4] nums2 = [5, 4, 4], then the output will be 2, because we can make 1 from nums1 to 6, so sum of nums1 is 10, then change any one 4 from nums2 to 1, so its sum is 10 also

To solve this, we will follow these steps −

  • sa := sum of all elements present in nums1

  • sb := sum of all elements present in nums2

  • if sa > sb, then

    • swap nums1 and nums2

    • swap sa and sb

  • sort the list nums1

  • sort the list nums2 in reverse order

  • res := 0

  • toadd := sb - sa

  • i := 0, j := 0

  • while toadd > 0, do

    • res := res + 1

    • if i < size of nums1 and j < size of nums2, then

      • resa := 6 - nums1[i]

      • resb := nums2[j] - 1

      • if resa > resb, then

        • toadd := toadd - resa

        • i := i + 1

      • otherwise,

        • toadd := toadd - resb

        • j := j + 1

      • otherwise when i < size of nums1, then

        • resa := 6 - nums1[i]

        • toadd := toadd - resa

        • i := i + 1

      • otherwise when j < size of nums2, then

        • resb := nums2[j] - 1

        • toadd := toadd - resb

        • j := j + 1

      • otherwise,

        • return -1

  • return res

Example

Let us see the following implementation to get better understanding

def solve(nums1, nums2):
   sa = sum(nums1)
   sb = sum(nums2)
   if sa > sb:
      nums1, nums2 = nums2, nums1
      sa, sb = sb, sa

   nums1.sort()
   nums2.sort(reverse=True)
   res = 0
   toadd = sb - sa
   i = 0
   j = 0
   while toadd > 0:
      res += 1
      if i < len(nums1) and j < len(nums2):
         resa = 6 - nums1[i]
         resb = nums2[j] - 1
         if resa > resb:
            toadd -= resa
            i += 1
         else:
            toadd -= resb
            j += 1
      elif i < len(nums1):
         resa = 6 - nums1[i]
         toadd -= resa
         i += 1
      elif j < len(nums2):
         resb = nums2[j] - 1
         toadd -= resb
         j += 1
      else:
         return -1

   return res

nums1 = [1, 4]
nums2 = [5, 4, 4]
print(solve(nums1, nums2))

Input

[2,1,4,3,5,4]

Output

2

Advertisements