Skip to content

Commit 51c1825

Browse files
authored
Implement solution for maximum task assignment problem
1 parent bb4e66c commit 51c1825

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
public:
3+
bool check(vector<int>& tasks, vector<int>& workers, int pills, int strength, int mid) {
4+
int pillsUsed = 0;
5+
multiset<int> st(begin(workers), begin(workers) + mid); //best mid workers
6+
7+
for(int i = mid-1; i >= 0; i--) {
8+
int reqrd = tasks[i];
9+
auto it = prev(st.end());
10+
11+
if(*it >= reqrd) {
12+
st.erase(it);
13+
} else if(pillsUsed >= pills) {
14+
return false;
15+
} else {
16+
//find the weakest worker which can do this strong task using pills
17+
auto weakestWorkerIt = st.lower_bound(reqrd - strength);
18+
if(weakestWorkerIt == st.end()) {
19+
return false;
20+
}
21+
st.erase(weakestWorkerIt);
22+
pillsUsed++;
23+
}
24+
}
25+
26+
return true;
27+
}
28+
int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {
29+
int m = tasks.size();
30+
int n = workers.size();
31+
32+
int l = 0;
33+
int r = min(m, n);
34+
35+
sort(begin(tasks), end(tasks));
36+
sort(begin(workers), end(workers), greater<int>());
37+
38+
int result = 0;
39+
40+
while(l <= r) {
41+
int mid = l + (r-l)/2;
42+
43+
if(check(tasks, workers, pills, strength, mid)) {
44+
result = mid;
45+
l = mid+1;
46+
} else {
47+
r = mid-1;
48+
}
49+
}
50+
51+
return result;
52+
53+
54+
}
55+
};

0 commit comments

Comments
 (0)