Problem Description
Given two arrays of integers, nums1 and nums2, where each integer is between 1 and 6 (inclusive), we can perform operations where we change any element in either array to any value between 1 and 6. The goal is to make the sums of the two arrays equal using the minimum number of operations, or return -1 if it is impossible.
Key Insights
- Determine which array has the smaller sum and which has the larger sum.
- The maximum adjustment per operation is 5 (either increasing a 1 to a 6 or decreasing a 6 to a 1).
- Use a greedy approach by selecting the operation that provides the maximum change (gain) first.
- Calculate all possible gains from both arrays: for the smaller-sum array, the gain is (6 - current_val) and for the larger-sum array, it is (current_val - 1).
- Sort these gains in descending order and apply them until the sum difference is closed.
Space and Time Complexity
Time Complexity: O(n) where n is the total number of elements in the two arrays. This covers summing the arrays and building and sorting the gains (sorting is O(n log n), but n is limited by constant factors due to the restricted range of values). Space Complexity: O(1) using extra space proportional to the size of gains, but since numbers range from 1 to 6, the counts can be managed with a fixed-size array if optimized further.
Solution
The solution follows these steps:
- Calculate the sums of the two arrays.
- If the sums are equal, return 0.
- Swap the arrays if needed so that nums1 always has the smaller sum.
- Compute the difference (diff) between the larger and smaller sums.
- For each element in nums1, determine the maximum gain by changing it to 6 (gain = 6 - element).
- For each element in nums2, determine the maximum gain by changing it to 1 (gain = element - 1).
- Combine all gains, sort them in descending order.
- Iteratively subtract the largest available gain from diff, and count the operations.
- If diff becomes 0 or negative, return the number of operations; otherwise, return -1 if all gains are exhausted.