forked from emotionless/Google_interview_question_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMin_Abs Difference_of_Server_Loads.cpp
53 lines (47 loc) · 1.15 KB
/
Min_Abs Difference_of_Server_Loads.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
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <vector>
using namespace std;
class MinAbsDiff {
public:
MinAbsDiff() {
dp.clear();
}
int minAbsDiff(vector<int> nums) {
int n = nums.size();
if (n == 0) return 0;
dp.resize(n + 1);
for(int i = 0; i <= n; i++) {
dp[i].clear();
}
int s = 0;
for(auto v : nums) {
s += v;
}
int m = s / 2;
for(int i = 0; i <= n; i++) {
dp[i].resize(m + 1);
dp[i][0] = 1;
}
int mx = 0;
for(int i = 0; i < n; i++) {
for(int j = nums[i]; j <= m; j++) {
dp[i+1][j] = dp[i+1][j] | dp[i][j - nums[i]];
if (dp[i+1][j]) {
//cout << j << endl;
mx = max(mx, j);
}
}
}
return abs((s - mx) - mx);
}
private:
vector<vector<bool>> dp;
};
int main() {
MinAbsDiff mad = MinAbsDiff ();
vector<int> input({1, 2, 3, 4, 5});
cout << mad.minAbsDiff(input) << endl;
vector<int> input1({10,10,9,9,2});
cout << mad.minAbsDiff(input1) << endl;
return 0;
}