|
| 1 | +// https://leetcode.com/problems/rearranging-fruits/ |
| 2 | +#include "xxx.hpp" |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + long long minCost(vector<int> &basket1, vector<int> &basket2) { |
| 7 | + map<int, int> cnt; |
| 8 | + for (auto &num : basket1) { |
| 9 | + cnt[num]++; |
| 10 | + } |
| 11 | + for (auto &num : basket2) { |
| 12 | + // not plus, minus |
| 13 | + // means the one with zero value is kept in this array |
| 14 | + cnt[num]--; |
| 15 | + } |
| 16 | + vector<int> exch; |
| 17 | + for (auto &kv : cnt) { |
| 18 | + // odd count, can not split |
| 19 | + if (kv.second & 1) { |
| 20 | + return -1; |
| 21 | + } |
| 22 | + for (int i = 0; i < abs(kv.second) / 2; i++) { |
| 23 | + exch.push_back(kv.first); |
| 24 | + } |
| 25 | + } |
| 26 | + int sz = exch.size(); |
| 27 | + nth_element(exch.begin(), exch.begin() + sz / 2, exch.end()); |
| 28 | + int minx = min(*min_element(basket1.begin(), basket1.end()), |
| 29 | + *min_element(basket2.begin(), basket2.end())); |
| 30 | + |
| 31 | + // Within each pair, there are two exchange methods: |
| 32 | + // 1. Direct exchange, the cost is the smaller number. |
| 33 | + // 2. Indirect exchange, choose another small number xxx as the |
| 34 | + // "intermediate", swap ai with x ans x with bj, the cost is 2x |
| 35 | + return accumulate(exch.begin(), exch.begin() + sz / 2, 0ll, |
| 36 | + [&](long long acc, int cur) -> long long { |
| 37 | + return acc + min(2 * minx, cur); |
| 38 | + }); |
| 39 | + } |
| 40 | +}; |
| 41 | + |
| 42 | +int main(int argc, char *argv[]) { |
| 43 | + Solution so; |
| 44 | + vector<int> input1{4, 2, 2, 2}; |
| 45 | + vector<int> input2{1, 4, 1, 2}; |
| 46 | + cout << so.minCost(input1, input2) << endl; |
| 47 | + return 0; |
| 48 | +} |
0 commit comments