-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathleetcode #2035
52 lines (47 loc) · 1.51 KB
/
leetcode #2035
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
43
44
45
46
47
48
49
50
51
52
class Solution {
public:
int minimumDifference(vector<int>& nums) {
const int n = nums.size() / 2;
const int sum = accumulate(begin(nums), end(nums), 0);
const int goal = sum / 2;
const vector<int> lNums(begin(nums), begin(nums) + n);
const vector<int> rNums(begin(nums) + n, end(nums));
int ans = INT_MAX;
vector<vector<int>> lSums(n + 1);
vector<vector<int>> rSums(n + 1);
dfs(lNums, 0, 0, 0, lSums);
dfs(rNums, 0, 0, 0, rSums);
for (int lCount = 0; lCount <= n; ++lCount) {
auto& l = lSums[lCount];
auto& r = rSums[n - lCount];
sort(begin(r), end(r));
for (const int lSum : l) {
const int i = firstGreaterEqual(r, goal - lSum);
if (i < r.size()) {
const int sumPartOne = sum - lSum - r[i];
const int sumPartTwo = sum - sumPartOne;
ans = min(ans, abs(sumPartOne - sumPartTwo));
}
if (i > 0) {
const int sumPartOne = sum - lSum - r[i - 1];
const int sumPartTwo = sum - sumPartOne;
ans = min(ans, abs(sumPartOne - sumPartTwo));
}
}
}
return ans;
}
private:
void dfs(const vector<int>& A, int i, int count, int path,
vector<vector<int>>& sums) {
if (i == A.size()) {
sums[count].push_back(path);
return;
}
dfs(A, i + 1, count + 1, path + A[i], sums);
dfs(A, i + 1, count, path, sums);
}
int firstGreaterEqual(const vector<int>& A, int target) {
return lower_bound(begin(A), end(A), target) - begin(A);
}
};