struct tuples{
int start;
int end;
int profit;
tuples(){
start = 0;
end = 0;
profit = 0;
}
tuples(int start, int end, int profit){
this->start = start;
this->end = end;
this->profit = profit;
}
static tuples make_tp(int start, int end, int profit){
return tuples(start, end, profit);
}
friend bool operator < (const tuples& lhs, const tuples& rhs) {
return lhs.start < rhs.start;
}
};
class Solution {
public:
int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
vector<tuples> v;
int n = startTime.size();
for(int i = 0; i < n; i++){
v.push_back(tuples::make_tp(startTime[i], endTime[i], profit[i]));
}
sort(v.begin(), v.end());
vector<int> dp(n);
dp[n - 1] = v[n - 1].profit;
for(int i = n - 2; i >= 0; i--){
dp[i] = max(v[i].profit, dp[i + 1]);
int left = i + 1;
int right = n - 1;
int nextJobs = -1;
while(left <= right)
{
int mid = left + (right - left) / 2;
if(v[mid].start >= v[i].end)
{
right = mid - 1;
nextJobs = mid;
}
else
{
left = mid + 1;
}
}
if(nextJobs != -1)
{
dp[i] = max(dp[i], dp[nextJobs] + v[i].profit);
}
}
return dp[0];
}
};