[LeetCode] Maximum Profit in Job Scheduling

1235. Maximum Profit in Job Scheduling

We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].

You’re given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.

If you choose a job that ends at time X you will be able to start another job that starts at time X.

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
class Solution {
vector<int> dp;
vector<int> bound;
int solution(vector<array<int,3>>& info, int c) {
if(dp[c]) return dp[c];
array<int,3> tmp = {info[c][1],INT_MIN,INT_MIN};
auto i = lower_bound(info.begin() + c, info.end(), tmp) - info.begin();

dp[c] = info[c][2];
bound[c] = i;
int ma = info.size();
for(; i < ma; i++) {
dp[c] = max(dp[c], solution(info,i) + info[c][2]);
ma = min(ma, bound[i]);
}
return dp[c];
}
public:
int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
int n = profit.size();
dp = vector<int>(n, 0);
bound = vector<int>(n, -1);
vector<array<int,3>> info;

for(int i = 0; i < n; i++) {
info.push_back({startTime[i], endTime[i], profit[i]});
}
sort(info.begin(), info.end());
int res = 0;
for(int i = 0; i < n; i++) {
res = max(res, solution(info, i));
n = min(n,bound[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/23/PS/LeetCode/maximum-profit-in-job-scheduling/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.