Skip to content

Commit 30b75bb

Browse files
authored
Create partition-array-into-two-arrays-to-minimize-sum-difference.cpp
1 parent 7ad0073 commit 30b75bb

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Time: O(n * 2^n)
2+
// Space: O(2^n)
3+
4+
class Solution {
5+
public:
6+
int minimumDifference(vector<int>& nums) {
7+
vector<int> left, right;
8+
for (int i = 0; i < size(nums); ++i) {
9+
if (i < size(nums) / 2) {
10+
left.emplace_back(nums[i]);
11+
} else {
12+
right.emplace_back(nums[i]);
13+
}
14+
}
15+
const auto& total1 = accumulate(cbegin(left), cend(left), 0);
16+
const auto& total2 = accumulate(cbegin(right), cend(right), 0);
17+
const int bound = (1 << size(left));
18+
unordered_map<int, vector<int>> sums;
19+
for (int mask = 0; mask < bound; ++mask) {
20+
int total = 0, bit = 1;
21+
for (const auto& x : left) {
22+
if (mask & bit) {
23+
total += x;
24+
}
25+
bit <<= 1;
26+
}
27+
sums[__builtin_popcount(mask)].emplace_back(2 * total - total1);
28+
}
29+
for (auto& [_, v] : sums) {
30+
sort(begin(v), end(v));
31+
}
32+
int result = numeric_limits<int>::max();
33+
for (int mask = 0; mask < bound; ++mask) {
34+
int total = 0, bit = 1;
35+
for (const auto& x : right) {
36+
if (mask & bit) {
37+
total += x;
38+
}
39+
bit <<= 1;
40+
}
41+
const int k = size(right) - __builtin_popcount(mask);
42+
const int diff = 2 * total - total2;
43+
const auto cit = lower_bound(cbegin(sums[k]), cend(sums[k]), -diff);
44+
if (cit != cend(sums[k])) {
45+
result = min(result, abs(*cit + diff));
46+
}
47+
if (cit != cbegin(sums[k])) {
48+
result = min(result, abs(*prev(cit) + diff));
49+
}
50+
}
51+
return result;
52+
}
53+
};

0 commit comments

Comments
 (0)