Problem
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 innums1
equal to the sum of values innums2
. Return -1
if it is not possible to make the sum of the two arrays equal.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums1.length, nums2.length <= 10^5
1 <= nums1[i], nums2[i] <= 6
Solution
Method 1 – Greedy Counting
Intuition
To make the sums equal, we want to maximize the reduction of the difference in each operation. We can either increase the smallest values or decrease the largest values, always picking the operation that reduces the difference the most at each step.
Approach
- Calculate the sums of both arrays. If already equal, return 0.
- If the sum of
nums1
is less thannums2
, swap them so thatnums1
always has the larger sum. - For each value in
nums1
, the maximum decrease isval - 1
. For each value innums2
, the maximum increase is6 - val
. - Collect all possible changes (decreases and increases) in a list.
- Sort the list in descending order.
- Greedily apply the largest possible change until the difference is reduced to 0 or less, counting the number of operations.
- If not possible, return -1.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
wheren
is the total number of elements in both arrays (for sorting). - 🧺 Space complexity:
O(n)
for the changes array.