Skip to content

Commit 60cd75d

Browse files
Create 1235-maximum-profit-in-job-scheduling.java
1 parent cc3a2a5 commit 60cd75d

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class Solution {
2+
int[][] intervals;
3+
Integer[] cache;
4+
5+
public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
6+
int n = startTime.length;
7+
intervals = new int[n][3];
8+
cache = new Integer[n];
9+
10+
for (int i = 0; i < n; i++) {
11+
intervals[i] = new int[]{startTime[i], endTime[i], profit[i]};
12+
}
13+
14+
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
15+
16+
return dfs(0);
17+
}
18+
19+
private int dfs(int i) {
20+
if (i == intervals.length) {
21+
return 0;
22+
}
23+
24+
if (cache[i] != null) {
25+
return cache[i];
26+
}
27+
28+
// don't include
29+
int res = dfs(i + 1);
30+
31+
// include
32+
int j = binarySearch(intervals, i, intervals[i][1]);
33+
cache[i] = res = Math.max(res, intervals[i][2] + dfs(j));
34+
35+
return res;
36+
}
37+
38+
private int binarySearch(int[][] intervals, int start, int target) {
39+
int left = start + 1;
40+
int right = intervals.length - 1;
41+
42+
while (left <= right) {
43+
int mid = left + (right - left) / 2;
44+
45+
if (intervals[mid][0] < target) {
46+
left = mid + 1;
47+
} else {
48+
right = mid - 1;
49+
}
50+
}
51+
52+
return left;
53+
}
54+
}

0 commit comments

Comments
 (0)