LeetCode 1775. Make the sum of the array equal through the minimum number of operations (greedy)

Title:

给你两个长度可能不等的整数数组 nums1 和 nums2 。两个数组中的所有值都在 16 之间(包含 16)。

每次操作中,你可以选择 任意 数组中的任意一个整数,将它变成 16 之间 任意 的值(包含 16)。

请你返回使 nums1 中所有数的和与 nums2 中所有数的和相等的最少操作次数。
如果无法使两个数组的和相等,请返回 -1 。

数据范围:
1 <= nums1.length, nums2.length <= 1e5
1 <= nums1[i], nums2[i] <= 6

solution:

统计两数组中各自[1,6]的数字个数,
贪心的选择变化范围大的数进行变化即可.

code:

class Solution {
    
    
public:
    int minOperations(vector<int>& a, vector<int>& b) {
    
    
        int c[7]={
    
    0};
        int cc[7]={
    
    0};
        for(auto i:a)c[i]++;
        for(auto i:b)cc[i]++;
        int s=0,ss=0;
        for(int i=1;i<=6;i++){
    
    
            s+=c[i]*i;
            ss+=cc[i]*i;
        }
        if(s>ss){
    
    
            swap(s,ss);
            swap(c,cc);
        }
        //s<ss
        int ans=0;
        for(int i=1,j=6;i<=5;i++,j--){
    
    
            int ma=(6-i)*c[i];
            if(s+ma>=ss){
    
    
                int t=(ss-s)/(6-i);
                if((ss-s)%(6-i))t++;
                ans+=t;
                s=ss;
                break;
            }else{
    
    
                s+=ma;
                ans+=c[i];
            }
            ma=(j-1)*cc[j];
            if(ss-ma<=s){
    
    
                int t=(ss-s)/(j-1);
                if((ss-s)%(j-1))t++;
                ans+=t;
                ss=s;
                break;
            }else{
    
    
                ss-=ma;
                ans+=cc[j];
            }
        }
        if(s!=ss)return -1;
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_44178736/article/details/114236574