Equal Sum Arrays With Minimum Number of Operations LeetCode solution in Python

1
class Solution:
2
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
3

4
# step1. determine the larger array and the smaller array, and get the difference on sum
5
sum1 = sum(nums1)
6
sum2 = sum(nums2)
7

8
if sum1 == sum2:
9
return 0
10
elif sum1 > sum2:
11
larger_sum_nums = nums1
12
smaller_sum_nums = nums2
13
else:
14
larger_sum_nums = nums2
15
smaller_sum_nums = nums1
16

17
sum_diff = abs(sum1 - sum2)
18

19
# step2. calculate the max "gain" at each position (how much difference we can reduce if operating on that position)
20
gains_in_larger_array = [num - 1 for num in larger_sum_nums]
21
gains_in_smaller_array = [6 - num for num in smaller_sum_nums]
22

23
# step3. sort the "gain" and check the least number of steps to reduce the difference to 0
24
gains = gains_in_larger_array + gains_in_smaller_array
25
gains.sort(reverse=True)
26

27
count = 0
28
target_diff = sum_diff
29

30
for i in range(len(gains)):
31
target_diff -= gains[i]
32
count += 1
33

34
if target_diff <= 0:
35
return count
36

37
# return -1 if the difference still cannot be reduced to 0 even after operating on all positions
38
return -1

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0