Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1775.html

1775. Equal Sum Arrays With Minimum Number of Operations

Level

Medium

Description

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 <= 10^5
  • 1 <= nums1[i], nums2[i] <= 6

Solution

Use greedy approach. First calculate the sum of nums1 and the sum of nums2 and determine whether it is possible to make two arrays have equal sum. Next count the occurrences of numbers from 1 to 6 in both arrays nums1 and nums2, and count the differences from 1 to 5. Use the difference between two sums and the differences to determine the minimum number of operations.

  • class Solution {
        public int minOperations(int[] nums1, int[] nums2) {
            int length1 = nums1.length, length2 = nums2.length;
            int minSum1 = length1, maxSum1 = 6 * length1, minSum2 = length2, maxSum2 = 6 * length2;
            if (minSum1 > maxSum2 || maxSum1 < minSum2)
                return -1;
            int sum1 = 0, sum2 = 0;
            int[] counts1 = new int[7];
            int[] counts2 = new int[7];
            for (int i = 0; i < length1; i++) {
                sum1 += nums1[i];
                counts1[nums1[i]]++;
            }
            for (int i = 0; i < length2; i++) {
                sum2 += nums2[i];
                counts2[nums2[i]]++;
            }
            if (sum1 == sum2)
                return 0;
            else if (sum1 < sum2)
                return getOperations(counts1, counts2, sum2 - sum1);
            else
                return getOperations(counts2, counts1, sum1 - sum2);
        }
    
        public int getOperations(int[] minCounts, int[] maxCounts, int difference) {
            int[] differences = new int[6];
            for (int i = 1; i < 6; i++)
                differences[6 - i] += minCounts[i];
            for (int j = 6; j > 1; j--)
                differences[j - 1] += maxCounts[j];
            int operations = 0;
            for (int i = 5; i > 0 && difference > 0; i--) {
                int count = differences[i];
                int maxReduce = i * count;
                if (maxReduce < difference) {
                    difference -= maxReduce;
                    operations += count;
                } else {
                    int curOperations = difference / i;
                    if (difference % i != 0)
                        curOperations++;
                    operations += curOperations;
                    difference = 0;
                }
            }
            return operations;
        }
    }
    
    ############
    
    class Solution {
        public int minOperations(int[] nums1, int[] nums2) {
            int s1 = Arrays.stream(nums1).sum();
            int s2 = Arrays.stream(nums2).sum();
            if (s1 == s2) {
                return 0;
            }
            if (s1 > s2) {
                return minOperations(nums2, nums1);
            }
            int d = s2 - s1;
            int[] cnt = new int[6];
            for (int v : nums1) {
                ++cnt[6 - v];
            }
            for (int v : nums2) {
                ++cnt[v - 1];
            }
            int ans = 0;
            for (int i = 5; i > 0; --i) {
                while (cnt[i] > 0 && d > 0) {
                    d -= i;
                    --cnt[i];
                    ++ans;
                }
            }
            return d <= 0 ? ans : -1;
        }
    }
    
  • // OJ: https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/
    // Time: O(M + N)
    // Space: O(1)
    class Solution {
        int getOp(int cnt[7], int diff) {
            int ans = 0;
            if (diff > 0) {
                for (int i = 1; i < 6; ++i) {
                    int d = 6 - i;
                    int q = min((diff + d - 1) / d, cnt[i]);
                    diff -= q * d;
                    ans += q;
                    if (diff <= 0) break;
                }
            } else {
                diff = -diff;
                for (int i = 6; i > 1; --i) {
                    int d = i - 1;
                    int q = min((diff + d - 1) / d, cnt[i]);
                    diff -= q * d;
                    ans += q;
                    if (diff <= 0) break;
                }
            }
            return ans;
        }
    public:
        int minOperations(vector<int>& A, vector<int>& B) {
            int M = A.size(), N = B.size();
            if (M > 6 * N || N > 6 * M) return -1;
            int ans = INT_MAX, cnta[7] = {}, cntb[7] = {}, sa = accumulate(begin(A), end(A), 0), sb = accumulate(begin(B), end(B), 0);
            for (int a : A) cnta[a]++;
            for (int b : B) cntb[b]++;
            for (int i = max(M, N), mx = 6 * min(M, N); i <= mx; ++i) {
                int op = getOp(cnta, i - sa) + getOp(cntb, i - sb);
                ans = min(ans, op);
            }
            return ans;
        }
    };
    
  • class Solution:
        def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
            s1, s2 = sum(nums1), sum(nums2)
            if s1 == s2:
                return 0
            if s1 > s2:
                return self.minOperations(nums2, nums1)
            arr = [6 - v for v in nums1] + [v - 1 for v in nums2]
            d = s2 - s1
            for i, v in enumerate(sorted(arr, reverse=True), 1):
                d -= v
                if d <= 0:
                    return i
            return -1
    
    ############
    
    # 1775. Equal Sum Arrays With Minimum Number of Operations
    # https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/
    
    class Solution:
        def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
            n1, n2 = len(nums1), len(nums2)
            if n1 * 6 < n2 or n1 > n2 * 6: return -1
            
            sum1, sum2 = sum(nums1), sum(nums2)
            if sum1 > sum2: return self.minOperations(nums2, nums1)
            
            nums1.sort()
            nums2.sort()
            
            i, j ,res = 0, n2 - 1, 0
            
            while sum2 > sum1:
                if (j < 0 or i < n1) and 6 - nums1[i] > nums2[j] - 1:
                    sum1 += 6 - nums1[i]
                    i += 1
                else:
                    sum2 -= nums2[j] - 1
                    j -= 1
                
                res += 1
                
            return res
    
    
  • func minOperations(nums1 []int, nums2 []int) (ans int) {
    	s1, s2 := sum(nums1), sum(nums2)
    	if s1 == s2 {
    		return 0
    	}
    	if s1 > s2 {
    		return minOperations(nums2, nums1)
    	}
    	d := s2 - s1
    	cnt := [6]int{}
    	for _, v := range nums1 {
    		cnt[6-v]++
    	}
    	for _, v := range nums2 {
    		cnt[v-1]++
    	}
    	for i := 5; i > 0; i-- {
    		for cnt[i] > 0 && d > 0 {
    			d -= i
    			cnt[i]--
    			ans++
    		}
    	}
    	if d <= 0 {
    		return
    	}
    	return -1
    }
    
    func sum(nums []int) (s int) {
    	for _, v := range nums {
    		s += v
    	}
    	return
    }
    

All Problems

All Solutions