Skip to content

Commit 5e1680c

Browse files
authored
Create maximum-profit-in-job-scheduling.cpp
1 parent 6678ae7 commit 5e1680c

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
7+
vector<tuple<int, int, int>> jobs;
8+
for (int i = 0; i < startTime.size(); ++i) {
9+
jobs.emplace_back(endTime[i], startTime[i], profit[i]);
10+
}
11+
sort(jobs.begin(), jobs.end());
12+
vector<pair<int, int>> dp = {{0, 0}};
13+
for (const auto& [e, s, p] : jobs) {
14+
const auto& it = prev(upper_bound(dp.cbegin(),
15+
dp.cend(),
16+
make_pair(s + 1, 0)));
17+
if (it->second + p > dp.back().second) {
18+
dp.emplace_back(e, it->second + p);
19+
}
20+
}
21+
return dp.back().second;
22+
}
23+
};
24+
25+
26+
// Time: O(nlogn)
27+
// Space: O(n)
28+
class Solution2 {
29+
public:
30+
int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
31+
vector<tuple<int, int, int>> min_heap;
32+
for (int i = 0; i < startTime.size(); ++i) {
33+
min_heap.emplace_back(startTime[i], endTime[i], profit[i]);
34+
}
35+
make_heap(min_heap.begin(), min_heap.end(), greater<>());
36+
int result = 0;
37+
while (!min_heap.empty()) {
38+
pop_heap(min_heap.begin(), min_heap.end(), greater<>());
39+
const auto [s, e, p] = min_heap.back();
40+
min_heap.pop_back();
41+
if (s < e) {
42+
min_heap.emplace_back(e, s, result + p);
43+
push_heap(min_heap.begin(), min_heap.end(), greater<>());
44+
} else {
45+
result = max(result, p);
46+
}
47+
}
48+
return result;
49+
}
50+
};

0 commit comments

Comments
 (0)