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
Solution: Greedy
Assuming sum(nums1) < sum(nums2),
sort both arrays
* scan nums1 from left to right, we need to increase the value form the smallest one.
* scan nums2 from right to left, we need to decrease the value from the largest one.
Each time, select the one with the largest delta to change.
e.g. nums1[i] = 2, nums[j] = 4, delta1 = 6 – 2 = 4, delta2 = 4 – 1 = 3, Increase 2 to 6 instead of decreasing 4 to 1.
Time complexity: O(mlogm + nlogn)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// Author: Huahua class Solution { public: int minOperations(vector<int>& nums1, vector<int>& nums2) { const int l1 = nums1.size(); const int l2 = nums2.size(); if (min(l1, l2) * 6 < max(l1, l2)) return -1; int s1 = accumulate(begin(nums1), end(nums1), 0); int s2 = accumulate(begin(nums2), end(nums2), 0); if (s1 > s2) return minOperations(nums2, nums1); sort(begin(nums1), end(nums1)); sort(begin(nums2), end(nums2)); int ans = 0; int i = 0; int j = l2 - 1; while (s1 != s2) { const int diff = s2 - s1; if (j == l2 || (i != l1 && 6 - nums1[i] >= nums2[j] - 1)) { const int x = min(6, nums1[i] + diff); s1 += x - nums1[i++]; } else { const int x = max(1, nums2[j] - diff); s2 += x - nums2[j--]; } ++ans; } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment