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.
Example 1:
Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].
- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].
- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].
Example 2:
Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
Output: -1
Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
Example 3:
Input: nums1 = [6,6], nums2 = [1]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].
- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].
- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].
Constraints:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[i] <= 6
假设 sum_1 是 nums1 中所有数字的加和, sum_2 是 nums2 中所有数字的加和
如果 sum1 > sum2, 那我们需要降低 nums1 中的数字或者升高 nums2 中的数字, 因为可选的数字就是 1-6, 所以每个数字所能做出的贡献是不同的:
nums1 中的 1 和 nums2 中的 6: 因为没法变化所以贡献是 0
nums1 中的 2 和 nums2 中的 5: 贡献是 1, 即 nums1 中的 2 可以变成 1, nums2 中的 5 可以变成 6
nums1 中的 3 和 nums2 中的 4: 贡献是 2
nums1 中的 4 和 nums2 中的 3: 贡献是 3
nums1 中的 5 和 nums2 中的 2: 贡献是 4
nums1 中的 6 和 nums2 中的 1: 贡献是 5
如果 sum1 < sum2 上面的情况会反过来, 即:
nums2 中的 1 和 nums1 中的 6: 因为没法变化所以贡献是 0
nums2 中的 2 和 nums1 中的 5: 贡献是 1, 即 nums1 中的 2 可以变成 1, nums2 中的 5 可以变成 6
nums2 中的 3 和 nums1 中的 4: 贡献是 2
nums2 中的 4 和 nums1 中的 3: 贡献是 3
nums2 中的 5 和 nums1 中的 2: 贡献是 4
nums2 中的 6 和 nums1 中的 1: 贡献是 5
我们把 nums1 和 nums2 中的各个数字分别计数, 然后求出 sum1 和 sum2 的差值, 最后从贡献大的数字开始, 看需要转变多少个数字才能填平差值
impl Solution {
pub fn min_operations(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
let mut counts_1 = vec![0; 6];
let mut sum_1 = 0i32;
for n in nums1 {
counts_1[n as usize - 1] += 1;
sum_1 += n;
}
let mut counts_2 = vec![0; 6];
let mut sum_2 = 0i32;
for n in nums2 {
counts_2[n as usize - 1] += 1;
sum_2 += n;
}
if sum_1 == sum_2 {
return 0;
}
let mut counts: Vec<usize> = counts_1
.into_iter()
.zip(counts_2.into_iter().rev())
.map(|(c1, c2)| (c1 + c2) as usize)
.collect();
if sum_1 > sum_2 {
counts.reverse();
}
let mut diff = (sum_1 - sum_2).abs() as usize;
let mut ans = 0;
let mut i = 0;
while diff > 0 {
if i == 6 {
return -1;
}
let d = 5 - i;
let total = d * counts[i];
if diff <= total {
ans += diff / d;
ans += if diff % d > 0 { 1 } else { 0 };
break;
}
diff -= total;
ans += counts[i];
i += 1;
}
ans as i32
}
}