forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-number-of-integers-to-choose-from-a-range-i.cpp
81 lines (78 loc) · 2.41 KB
/
maximum-number-of-integers-to-choose-from-a-range-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
// Time: O(b)
// Space: O(b)
// math
class Solution {
public:
int maxCount(vector<int>& banned, int n, long long maxSum) {
int k = min(static_cast<int>(((-1 + sqrt(1 + 8 * maxSum)) / 2)), n); // k = argmax((k+1)*k//2 <= maxSum)
int64_t total = static_cast<int64_t>(k + 1) * k / 2;
int result = k;
unordered_set<int> lookup(cbegin(banned), cend(banned));
for (const auto& x : lookup) {
if (x <= k) {
total -= x;
--result;
}
}
for (int i = k + 1; i <= n; ++i) {
if (lookup.count(i)) {
continue;
}
if (total + i > maxSum) {
break;
}
total += i;
++result;
}
return result;
}
};
// Time: O(blogb + logn * logb)
// Space: O(b)
// binary search, prefix sum
class Solution2 {
public:
int maxCount(vector<int>& banned, int n, long long maxSum) {
unordered_set<int> banned_set(cbegin(banned), cend(banned));
vector<int> sorted_banned(cbegin(banned_set), cend(banned_set));
sort(begin(sorted_banned), end(sorted_banned));
vector<int64_t> prefix(size(sorted_banned) + 1);
for (int i = 0; i < size(sorted_banned); ++i) {
prefix[i + 1] = prefix[i] + sorted_banned[i];
}
const auto& check = [&](const int64_t x) {
return (x + 1) * x / 2 - prefix[distance(cbegin(sorted_banned), upper_bound(cbegin(sorted_banned), cend(sorted_banned), x))] <= maxSum;
};
int left = 1, right = n;
while (left <= right) {
const auto mid = left + (right - left) / 2;
if (!check(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right - distance(cbegin(sorted_banned), upper_bound(cbegin(sorted_banned), cend(sorted_banned), right));
}
};
// Time: O(n)
// Space: O(b)
// greedy
class Solution3 {
public:
int maxCount(vector<int>& banned, int n, int maxSum) {
unordered_set<int> lookup(cbegin(banned), cend(banned));
int result = 0;
for (int i = 1, total = 0; i <= n; ++i) {
if (lookup.count(i)) {
continue;
}
if (total + i > maxSum) {
break;
}
total += i;
++result;
}
return result;
}
};