-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
maximum-total-reward-using-operations-i.cpp
102 lines (96 loc) · 3.08 KB
/
maximum-total-reward-using-operations-i.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
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
92
93
94
95
96
97
98
99
100
101
102
// Time: O(nlogn + r^2), r = max(rewardValues)
// Space: O(r)
// sort, dp, bitset
class Solution {
public:
int maxTotalReward(vector<int>& rewardValues) {
static const int MAX_VALUE = 20000;
unordered_set<int> v_set(cbegin(rewardValues), cend(rewardValues));
vector<int> sorted_v(cbegin(v_set), cend(v_set));
sort(begin(sorted_v), end(sorted_v));
bitset<(MAX_VALUE - 1) + 1> dp, mask;
dp[0] = true;
int i = 0;
for (int i = 0, j = 0; i + 1 < size(sorted_v); ++i) {
while (j < sorted_v[i]) {
mask[j++] = true;
}
dp |= (dp & mask) << sorted_v[i];
}
int result = sorted_v.back() - 1;
for (; !dp[result]; --result);
return sorted_v.back() + result;
}
};
// Time: O(nlogn + r^2), r = max(rewardValues)
// Space: O(r)
// sort, dp, bitset
class Solution2 {
public:
int maxTotalReward(vector<int>& rewardValues) {
static const int MAX_VALUE = 20000;
unordered_set<int> v_set(cbegin(rewardValues), cend(rewardValues));
vector<int> sorted_v(cbegin(v_set), cend(v_set));
sort(begin(sorted_v), end(sorted_v));
bitset<(MAX_VALUE * 2 - 1) + 1> dp, mask;
dp[0] = true;
int i = 0;
for (int i = 0, j = 0; i < size(sorted_v); ++i) {
while (j < sorted_v[i]) {
mask[j++] = true;
}
dp |= (dp & mask) << sorted_v[i];
}
int result = 2 * sorted_v.back() - 1;
for (; !dp[result]; --result);
return result;
}
};
// Time: O(nlogn + r^2), r = max(rewardValues)
// Space: O(r)
// sort, dp
class Solution3 {
public:
int maxTotalReward(vector<int>& rewardValues) {
unordered_set<int> v_set(cbegin(rewardValues), cend(rewardValues));
vector<int> sorted_v(cbegin(v_set), cend(v_set));
sort(begin(sorted_v), end(sorted_v));
const int mx = sorted_v.back();
vector<bool> dp((mx - 1) + 1);
dp[0] = true;
for (int i = 0; i + 1 < size(sorted_v); ++i) {
for (int x = 0; x < min(sorted_v[i], mx - sorted_v[i]); ++x) {
if (dp[x]) {
dp[sorted_v[i] + x] = dp[x];
}
}
}
int result = mx - 1;
for (; !dp[result]; --result);
return mx + result;
}
};
// Time: O(nlogn + r^2), r = max(rewardValues)
// Space: O(r)
// sort, dp
class Solution4 {
public:
int maxTotalReward(vector<int>& rewardValues) {
unordered_set<int> v_set(cbegin(rewardValues), cend(rewardValues));
vector<int> sorted_v(cbegin(v_set), cend(v_set));
sort(begin(sorted_v), end(sorted_v));
const int mx = sorted_v.back();
vector<bool> dp((mx * 2 - 1) + 1);
dp[0] = true;
for (int i = 0; i < size(sorted_v); ++i) {
for (int x = 0; x < sorted_v[i]; ++x) {
if (dp[x]) {
dp[sorted_v[i] + x] = dp[x];
}
}
}
int result = 2 * mx - 1;
for (; !dp[result]; --result);
return result;
}
};