generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.cpp
33 lines (29 loc) · 1.04 KB
/
solution.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
#include <algorithm>
#include <numeric>
#include <vector>
class Solution {
public:
std::vector<int> fairCandySwap(
std::vector<int>& aliceSizes, std::vector<int>& bobSizes) {
std::sort(aliceSizes.begin(), aliceSizes.end());
std::sort(bobSizes.begin(), bobSizes.end());
const auto aliceSum = std::accumulate(aliceSizes.begin(), aliceSizes.end(), 0);
const auto bobSum = std::accumulate(bobSizes.begin(), bobSizes.end(), 0);
if (aliceSum <= bobSum) {
const auto diff = (bobSum - aliceSum) / 2;
auto bobIt = bobSizes.begin();
for (const auto alice : aliceSizes) {
bobIt = std::lower_bound(bobIt, bobSizes.end(), alice + diff);
if (alice + diff == *bobIt) return {alice, *bobIt};
}
} else {
const auto diff = (aliceSum - bobSum) / 2;
auto aliceIt = aliceSizes.begin();
for (const auto bob : bobSizes) {
aliceIt = std::lower_bound(aliceIt, aliceSizes.end(), bob + diff);
if (bob + diff == *aliceIt) return {*aliceIt, bob};
}
}
return {};
}
};