-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
33 lines (29 loc) · 957 Bytes
/
Copy pathsolution.cpp
File metadata and controls
33 lines (29 loc) · 957 Bytes
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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxProfit(vector<vector<int>> &jobs)
{
int n = jobs.size();
// Sort by end time
sort(jobs.begin(), jobs.end(), [](const auto &a, const auto &b)
{ return a[1] < b[1]; });
vector<int> ends(n);
for (int i = 0; i < n; ++i)
ends[i] = jobs[i][1];
// Use long long internally to be safe with sums
vector<long long> dp(n, 0);
for (int i = 0; i < n; ++i)
{
long long take = jobs[i][2];
// Find rightmost job j with ends[j] <= jobs[i][0]
int j = upper_bound(ends.begin(), ends.begin() + i, jobs[i][0]) - ends.begin() - 1;
if (j >= 0)
take += dp[j];
long long skip = (i ? dp[i - 1] : 0);
dp[i] = max(skip, take);
}
return (int)dp.back();
}
};