[LeetCode] Equal Sum Arrays With Minimum Number of Operations

1775. Equal Sum Arrays With Minimum Number of Operations

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int minOperations(vector<int>& nums1, vector<int>& nums2) {
int sum1 = accumulate(begin(nums1), end(nums1), 0), sum2 = accumulate(begin(nums2), end(nums2), 0);
int res = 0, diff = abs(sum1 - sum2);
if(!diff)
return res;

list<int> l;
l.insert(end(l), begin(nums1), end(nums1));
auto it = prev(end(l));
l.insert(end(l), begin(nums2), end(nums2));
transform(begin(l), next(it), begin(l), [sum1, sum2](int num) { return sum1 > sum2 ? num - 1 : 6 - num; });
transform(next(it), end(l), next(it), [sum1, sum2](int num) { return sum1 > sum2 ? 6 - num : num - 1; });
l.sort(greater<int>());
for(auto& num : l) {
res++;
diff -= num;
if(diff <= 0)
return res;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/28/PS/LeetCode/equal-sum-arrays-with-minimum-number-of-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.