Maximum Profit in Job Scheduling
Problem
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
.
Solution Approach
Expected Time complexity:
Click - to see solution code
- C++
class Solution {
public:
int jobScheduling(vector<int>& startTime, vector<int>& endTime,
vector<int>& profit) {
vector<vector<int>> v;
int n = startTime.size();
v.push_back({INT_MIN, INT_MIN, INT_MIN});
for (int i = 0; i < n; i++) {
v.push_back({endTime[i], startTime[i], profit[i]});
}
sort(v.begin(), v.end());
sort(endTime.begin(), endTime.end());
vector<vector<int>> dp(n + 1, vector<int>(2));
for (int i = 1; i <= n; i++) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]);
dp[i][1] = v[i][2];
int indx = upper_bound(endTime.begin(), endTime.end(), v[i][1]) -
endTime.begin();
dp[i][1] += max(dp[indx][0], dp[indx][1]);
}
return max(dp[n][0], dp[n][1]);
}
};