Program to find equal sum arrays with minimum number of operations in Python

PythonServer Side ProgrammingProgramming

Suppose we have two arrays of called nums1 and nums2. The values in the arrays are between 1 and 6(inclusive). In one operation, we can update any value in any of the arrays to any value between 1 and 6. We have to find the minimum number of operations needed to make the sum of values in nums1 equal to the sum of values in nums2. We have to return -1 if it is not possible.

So, if the input is like nums1 = [1,5,6], nums2 = [4,1,1], then the output will be 2 because we can change nums2 from [4,1,1] to [4,1,6] in first operation, and [4,2,6] in second operation to make its same equal to nums1.

To solve this, we will follow these steps −

  • s1 := sum of all elements in nums1

  • s2 := sum of all elements in nums2

  • sort the list nums1 and sort the list nums2

  • if s1 > s2, then

    • swap nums1 and nums2

    • swap s1 and s2

  • ans := 0

  • left := 0, right := size of nums2 -1

  • while left < length of nums1 or right >= 0, do

    • if s1 is same as s2, then

      • return ans

    • curr_left := nums1[left] if left < length of nums1, otherwise 7

    • curr_right := nums2[right] if right >= 0 otherwise 0

    • if 6-curr_left >= curr_right-1, then

      • s1 := s1 + minimum of 6-curr_left and s2-s1

      • left := left + 1

    • otherwise,

      • s2 := s2 - minimum of curr_right-1 and s2-s1

      • right := right - 1

    • ans := ans + 1

  • return -1 if s1 is not same as s2 otherwise ans

Example

Let us see the following implementation to get better understanding −

def solve(nums1, nums2):
   s1 = sum(nums1)
   s2 = sum(nums2)
   nums1.sort()
   nums2.sort()
   if s1>s2:
      nums1, nums2 = nums2, nums1
      s1, s2 = s2, s1

   ans = 0
   left, right = 0, len(nums2)-1
   while(left<len(nums1) or right>=0):
      if s1==s2:
         return ans
      curr_left = nums1[left] if left<len(nums1) else 7
      curr_right = nums2[right] if right>=0 else 0
      if 6-curr_left>=curr_right-1:
         s1+= min(6-curr_left, s2-s1)
         left+=1
      else:
         s2-= min(curr_right-1, s2-s1)
         right-=1
      ans+=1
   return -1 if s1!=s2 else ans

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

Input

[1,5,6], [4,1,1]

Output

2
raja
Published on 06-Oct-2021 10:52:18
Advertisements