-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathMinAbsSum.cpp
More file actions
91 lines (78 loc) · 2.29 KB
/
MinAbsSum.cpp
File metadata and controls
91 lines (78 loc) · 2.29 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// reference: https://stackoverflow.com/a/44901707/365229
#include <vector>
#include <set>
int solution1(vector<int> &A) {
if (A.size() == 0) return 0;
set<int> sums, tmpSums;
sums.insert(abs(A[0]));
for (auto it = begin(A) + 1; it != end(A); ++it)
{
for (auto s : sums)
{
tmpSums.insert(abs(s + abs(*it)));
tmpSums.insert(abs(s - abs(*it)));
}
sums = tmpSums;
tmpSums.clear();
}
return *sums.begin();
}
// reference: https://github.com/Behrouz-m/Codility/blob/master/Docs/solutions/solution-min-abs-sum.pdf
// O(N^2.M)
// result=72% : https://app.codility.com/demo/results/trainingQW8QE8-SDF/
int solution2(vector<int>& A) {
const int N = A.size();
if (N == 0)
return 0;
int MaxVal = 0;
for (int i = 0; i < N; i++) {
A[i] = abs(A[i]);
MaxVal = max(MaxVal, A[i]);
}
const int Sum = std::accumulate(A.begin(), A.end(), 0);
vector<int> dp(Sum + 1, 0);
dp[0] = 1;
for (int j = 0; j < N; j++)
for (int i = Sum; i > -1; i--)
if (dp[i] == 1 and i + A[j] <= Sum)
dp[i + A[j]] = 1;
int result = Sum;
for (int i = 0; i < Sum / 2 + 1; i++)
if (dp[i] == 1)
result = min(result, Sum - 2 * i);
return result;
}
// O(N.M^2)
// result=100% = https://app.codility.com/demo/results/training226XH9-8VA/
int solution_golden(vector<int>& A) {
const int N = A.size();
if (N == 0)
return 0;
int MaxVal = 0;
for (int i = 0; i < N; i++) {
A[i] = abs(A[i]);
MaxVal = max(MaxVal, A[i]);
}
const int Sum = std::accumulate(A.begin(), A.end(), 0);
vector<int> count(MaxVal + 1, 0);
for (int i = 0; i < N; i++)
count[A[i]]++;
vector<int> dp(Sum + 1, -1);
dp[0] = 0;
for (int a = 1; a <= MaxVal; a++) {
if (count[a]>0) {
for (int j = 0; j < Sum; j++) {
if (dp[j] >= 0)
dp[j] = count[a];
else if (j >= a && dp[j - a] > 0)
dp[j] = dp[j - a] - 1;
}
}
}
int result = Sum;
for (int i = 0; i < Sum / 2 + 1; i++) {
if (dp[i] >= 0)
result = min(result, Sum - 2 * i);
}
return result;
}