原题题目
代码实现(首刷TLE 24/27)
class Solution {
public:int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
int size = startTime.size(),ret = -1;vector<vector<int>> temp;for(int i=0;i<size;++i)temp.push_back({
startTime[i],endTime[i],profit[i]});vector<int> dp(size+1,0);sort(temp.begin(),temp.end(),[](const vector<int>& a,const vector<int>& b){
return a[1]<b[1];});for(int i=0;i<size;i++){
dp[i] = profit[i];for(int j=0;j<i;j++){
if(endTime[j] <= startTime[i])dp[i] = max(dp[i],dp[j]+profit[i]);else break;}ret = max(dp[i],ret);}return ret;}
};
代码实现(二分加速给我绕晕了 cv别人的二分加速代码)
class Solution {
public:int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
int n = startTime.size();vector<int> id(n);iota(id.begin(), id.end(), 0);sort(id.begin(), id.end(),[&](auto a, auto b){
return endTime[a] < endTime[b];});map<int,int> dp;dp[0] = 0;dp[endTime[id[0]]] = profit[id[0]];int ans = profit[id[0]];for(int i = 1; i < n; i++){
int idx = id[i];auto it = dp.upper_bound(startTime[idx]);int dp_prev = (--it)->second;dp[endTime[idx]] = max(ans, max(dp[endTime[idx]], dp_prev+profit[idx]));ans = max(ans, dp[endTime[idx]]);}return ans;}
};