-
Notifications
You must be signed in to change notification settings - Fork 1
/
045_Job Sequencing Problem.cpp
82 lines (56 loc) · 1.64 KB
/
045_Job Sequencing Problem.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
// TC -> O(n (log n)) + O(n * maxDeadline) => O(n * maxDeadline)
// SC -> O(maxDeadline)
#include <bits/stdc++.h>
int jobScheduling(vector<vector<int>> &jobs)
{
// Write your code here
int n = jobs.size();
int maxProfit = 0, maxDeadline = 0;
sort(jobs.begin(), jobs.end(), [&](const vector<int> &a, const vector<int> &b){
return a[1] > b[1];
});
for(auto itr : jobs)
maxDeadline = max(maxDeadline, itr[0]);
vector<bool> slots(maxDeadline + 1, false);
for(int i = 0; i < n; ++i)
{
for(int j = jobs[i][0]; j > 0; --j)
{
if(!slots[j])
{
slots[j] = true;
maxProfit += jobs[i][1];
break;
}
}
}
return maxProfit;
}
// Another Approach
// TC -> O(N *log max(N, maxDeadline))
// SC -> O(maxDeadline)
#include <bits/stdc++.h>
int jobScheduling(vector<vector<int>> &jobs)
{
// Write your code here
int n = jobs.size();
int maxProfit = 0, maxDeadline = 0;
sort(jobs.begin(), jobs.end(), [&](const vector<int>&a, const vector<int>& b){
return a[1] > b[1];
});
for(auto itr : jobs)
maxDeadline = max(maxDeadline, itr[0]);
set<int, greater<int>> used;
for(int i = 1; i <= maxDeadline; ++i)
used.insert(i);
for(int i = 0; i < n; ++i)
{
int currDeadline = jobs[i][0];
if(used.empty() or currDeadline < *used.rbegin())
continue;
int availableSlot = *used.lower_bound(currDeadline);
maxProfit += jobs[i][1];
used.erase(availableSlot);
}
return maxProfit;
}