-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
maximum-number-of-tasks-you-can-assign.cpp
90 lines (84 loc) · 2.85 KB
/
maximum-number-of-tasks-you-can-assign.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
// Time: O(n * (logn)^2)
// Space: O(n)
class Solution {
public:
int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {
sort(begin(tasks), end(tasks));
sort(begin(workers), end(workers));
int left = 1, right = min(size(tasks), size(workers));
while (left <= right) {
const auto& mid = left + (right - left) / 2;
if (!check(tasks, workers, pills, strength, mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}
private:
bool check(const vector<int>& tasks, const vector<int>& workers,
int pills, int strength,
int x) {
multiset<int> t(cbegin(tasks), cbegin(tasks) + x);
for (int i = size(workers) - x; i < size(workers); ++i) { // enumerate from the weakest worker to the strongest worker, greedily assign him to the hardest task which he can do
auto it = t.upper_bound(workers[i]);
if (it != begin(t)) {
t.erase(prev(it));
continue;
}
if (pills) {
it = t.upper_bound(workers[i] + strength);
if (it != begin(t)) {
t.erase(prev(it));
--pills;
continue;
}
}
return false;
}
return true;
}
};
// Time: O(n * (logn)^2)
// Space: O(n)
class Solution2 {
public:
int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {
sort(rbegin(tasks), rend(tasks));
sort(begin(workers), end(workers));
int left = 1, right = min(size(tasks), size(workers));
while (left <= right) {
const auto& mid = left + (right - left) / 2;
if (!check(tasks, workers, pills, strength, mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}
private:
bool check(const vector<int>& tasks, const vector<int>& workers,
int pills, int strength,
int x) {
multiset<int> w(cbegin(workers) + (size(workers) - x), cend(workers));
for (int i = size(tasks) - x; i < size(tasks); ++i) { // enumerate from the hardest task to the easiest task, greedily assign it to the weakest worker whom it can be done by
auto it = w.lower_bound(tasks[i]);
if (it != end(w)) {
w.erase(it);
continue;
}
if (pills) {
it = w.lower_bound(tasks[i] - strength);
if (it != end(w)) {
w.erase(it);
--pills;
continue;
}
}
return false;
}
return true;
}
};