forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-total-cost-to-make-arrays-unequal.cpp
42 lines (41 loc) · 1.38 KB
/
minimum-total-cost-to-make-arrays-unequal.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
// Time: O(n)
// Space: O(n)
// greedy
class Solution {
public:
long long minimumTotalCost(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> cnt;
int64_t result = 0;
for (int i = 0; i < size(nums1); ++i) {
if (nums1[i] != nums2[i]) {
continue;
}
++cnt[nums1[i]];
result += i;
}
if (empty(cnt)) {
return 0;
}
const int majority = max_element(cbegin(cnt), cend(cnt),
[](const auto& a, const auto& b) {
return a.second < b.second;
})->first;
int remain = cnt[majority] - (accumulate(cbegin(cnt), cend(cnt), 0,
[](const auto& total, const auto& x) {
return total + x.second;
}) - cnt[majority]);
if (remain <= 0) {
return result;
}
for (int i = 0; i < size(nums1); ++i) {
if (nums1[i] == nums2[i] || nums1[i] == majority || nums2[i] == majority) {
continue;
}
result += i;
if (--remain == 0) {
return result;
}
}
return -1;
}
};