7. Equal Sum Arrays With Minimum Number of Operations
You are given two arrays of integers nums1
and nums2
, possibly of different lengths. The values in the arrays are between 1
and 6
, inclusive.
In one operation, you can change any integer's value in any of the arrays to any value between 1
and 6
, inclusive.
Return the minimum number of operations required to make the sum of values in nums1
equal to the sum of values in nums2
. Return -1
if it is not possible to make the sum of the two arrays equal.
Solution: (Greedy)
1.In order to make the two sum's equal, we need either to increase to 6
the numbers in the smaller sum array or decrease to 1
the numbers in the bigger sum array
2. Since we want to complete the task with minimum operations, it is optimal to choose the greater between the increase and decrease. Hence this is a greedy algorithm.
Note:
If all numbers in an array increasing to 6
still ends up with a sum less than the sum of the other array with all numbers decreasing to 1
's, then it is impossible to make their sums equal.
Time Complexity: O max(n + m)
Last updated