【Title】*1775. Make the sum of the arrays equal by the least number of operations
You are given two integer arrays nums1 and nums2 of possibly unequal length. All values in both arrays are between 1 and 6 inclusive.
In each operation, you can choose any integer in any array and turn it into any value between 1 and 6 (including 1 and 6).
Please return the minimum number of operations that make the sum of all numbers in nums1 equal to the sum of all numbers in nums2. Returns -1 if the sum of the two arrays cannot be made equal.
Example 1:
输入:nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
输出:3
解释:你可以通过 3 次操作使 nums1 中所有数的和与 nums2 中所有数的和相等。以下数组下标都从 0 开始。
- 将 nums2[0] 变为 6 。 nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2] 。
- 将 nums1[5] 变为 1 。 nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2] 。
- 将 nums1[2] 变为 2 。 nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2] 。
Example 2:
输入:nums1 = [1,1,1,1,1,1,1], nums2 = [6]
输出:-1
解释:没有办法减少 nums1 的和或者增加 nums2 的和使二者相等。
Example 3:
输入:nums1 = [6,6], nums2 = [1]
输出:3
解释:你可以通过 3 次操作使 nums1 中所有数的和与 nums2 中所有数的和相等。以下数组下标都从 0 开始。
- 将 nums1[0] 变为 2 。 nums1 = [2,6], nums2 = [1] 。
- 将 nums1[1] 变为 2 。 nums1 = [2,2], nums2 = [1] 。
- 将 nums2[0] 变为 4 。 nums1 = [2,2], nums2 = [4] 。
hint:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[i] <= 6
[Problem-solving ideas 1] Sorting + Greedy
The sum range of an array with length n is [n,6n]. If the sum ranges of the two arrays do not intersect, then return -1 directly. Then calculate the difference between the sums of the two arrays, and record it as d (set to be greater than or equal to 0, and the sum of array 1 is greater than or equal to the sum of array 2), then the purpose is to reduce d to no more than 0, you can select the largest number from nums1, try to reduce it to 1 or find the smallest number from nums2 and increase it to 6, choose the one with the larger change value, and subtract the difference from d until d is exhausted.
class Solution {
public int minOperations(int[] nums1, int[] nums2) {
int m=nums1.length,n=nums2.length;
if(m>n*6||n>m*6){
return -1;}
int d=0;
for(int i=0;i<m;i++){
d+=nums1[i];}
for(int i=0;i<n;i++){
d-=nums2[i];}
return minOp(nums1,nums2,d);
}
int minOp(int nums1[],int nums2[],int d){
if(d==0){
return 0;}
if(d<0){
return minOp(nums2,nums1,-d);}
//nums1的总和大于nums2的总和,需要减少nums1或者增加nums2
Arrays.sort(nums1);
Arrays.sort(nums2);
int a=nums1.length-1,b=0,ans=0;
while(d>0){
ans++;
if(a<0||b<nums2.length&&nums1[a]-1<=6-nums2[b]){
d-=6-nums2[b];
b++;
}
else{
d-=nums1[a]-1;
a--;
}
}
return ans;
}
}