-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmaximum-total-reward-using-operations-ii.cpp
52 lines (48 loc) · 1.57 KB
/
maximum-total-reward-using-operations-ii.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
// 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 = 50000;
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 = 50000;
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;
}
};