Approach
this is a dp like problem, we maintain for each endTime what is the best profit, then for the next subproblem, we just combine the sub-solution for taking current interval or not. If we take hte current interval, we use the upper_bound to get the best cost that end before the starting time of current interval, otherwise we take the privious solution.
One part that we need to be careful with is the duplicated endTime, we need to maintain the max if there are multiple intervals with the same endTime.
The timing complexity is O(NlgN) for both the sorting and the DP part.
Anothter part is to have a better way for writting the code. This is what I learned: (1) using v.rbegin() instead of --v.end(), (2) use prev(it) instead of --it
Code
class Solution {
public:
int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
int n = profit.size();
map<int,int> memo; // idx, best profit
vector<vector<int>> interval;
interval.reserve(n);
for(int i = 0 ; i < n ; ++i) {
interval.push_back({startTime[i], endTime[i], profit[i]});
}
sort(interval.begin(), interval.end(), [](auto& i1, auto& i2){return i1[1] < i2[1];});
memo.insert({interval[0][1], interval[0][2]});
for(int i = 1 ; i < n ; ++i) {
int cost1 = (--memo.end())->second;
auto it = memo.upper_bound(interval[i][0]);
int cost2 = interval[i][2] + (it == memo.begin() ? 0 : (--it)->second);
memo.insert({interval[i][1], max(cost1, cost2)});
memo[interval[i][1]] = max(memo[interval[i][1]], max(cost1, cost2));
}
return (--memo.end())->second;
}
};