Find non-overlapping jobs with maximum cost | Yaozong's Blog
Given a set of n jobs with [start time, end time, cost] find a subset so that no 2 jobs overlap and the cost is maximum.
Solution: sort + binary search + dynamic programming O(nlogn)
Read full article from
Find non-overlapping jobs with maximum cost | Yaozong's Blog
Given a set of n jobs with [start time, end time, cost] find a subset so that no 2 jobs overlap and the cost is maximum.
Solution: sort + binary search + dynamic programming O(nlogn)
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
struct Interval
{
int start;
int end;
int cost;
Interval(): start(0), end(0), cost(0) {}
Interval(int s, int e, int c): start(s), end(e), cost(c) {}
};
int sort_comp(const Interval& a, const Interval& b) {
return a.end < b.end;
}
class Solution
{
public:
int nonoverlap_max_cost(vector<Interval>& arr)
{
if(arr.size() == 0)
return 0;
sort(arr.begin(), arr.end(), sort_comp);
vector<int> dp(arr.size(), 0);
dp[0] = arr[0].cost;
for(int i = 1; i < arr.size(); ++i) {
int start = arr[i].start;
int idx = binary_search(arr, 0, i - 1, start);
dp[i] = max(dp[i-1], arr[i].cost + (idx == -1 ? 0 : dp[idx]));
}
return dp.back();
}
int binary_search(vector<Interval>& arr, int start, int end, int query) {
int left = start, right = end;
while(left < right)
{
int mid = (left + right + 1) / 2;
if(arr[mid].end <= start)
left = mid;
else
right = mid - 1;
}
if(arr[left].end > query)
return left - 1;
else
return left;
}
};
|