Posted on

Description

Submission

class Solution {
public:
    int minOperations(vector<int>& nums1, vector<int>& nums2) {
        int sum1 = accumulate(nums1.begin(), nums1.end(), 0);
        int sum2 = accumulate(nums2.begin(), nums2.end(), 0);

        if(sum1 < sum2) {
            swap(nums1, nums2);
            swap(sum1, sum2);
        }

        int gap = sum1 - sum2;
        int n = nums1.size(), m = nums2.size();

        sort(nums1.begin(), nums1.end(), greater<int>());
        sort(nums2.begin(), nums2.end());

        int i = 0, j = 0, ret = 0;
        for(; i < n && j < m && gap > 0; ++ret) {
            int gap1 = nums1[i] - 1;
            int gap2 = 6 - nums2[j];
            if(gap1 > gap2) {
                gap -= gap1;
                ++i;
            } else {
                gap -= gap2;
                ++j;
            }
        }

        if(gap <= 0) return ret;

        if(i == n) {
            for( ; j < m && gap > 0; ++j, ++ret) gap -= 6 - nums2[j];
        } else {
            for( ; i < n && gap > 0; ++i, ++ret) gap -= nums1[i] - 1;
        }

        if(gap <= 0) return ret;

        return -1;
    }
};

Bucket sort will make a faster solution.

Leave a Reply

Your email address will not be published. Required fields are marked *