1
+ class Solution {
2
+ class Job implements Comparable <Job > {
3
+ int start ;
4
+ int end ;
5
+ int profit ;
6
+ public Job (int start , int end , int profit ) {
7
+ this .start = start ;
8
+ this .end = end ;
9
+ this .profit = profit ;
10
+ }
11
+ @ Override
12
+ public int compareTo (Job o ) {
13
+ int c = end - o .end ;
14
+ if (c != 0 ) {
15
+ return c ;
16
+ }
17
+ return start - o .start ;
18
+ }
19
+ }
20
+ public int jobScheduling (int [] startTime , int [] endTime , int [] profit ) {
21
+ Job [] jobs = new Job [profit .length ];
22
+ for (int i = 0 ; i < profit .length ; i ++) {
23
+ jobs [i ] = new Job (startTime [i ], endTime [i ], profit [i ]);
24
+ }
25
+ Arrays .sort (jobs );
26
+
27
+ profit = new int [profit .length ];
28
+ profit [0 ] = jobs [0 ].profit ;
29
+ for (int i = 1 ; i < profit .length ; i ++) {
30
+ int lastMaxSum = foundMaxProfitBeforeStart (jobs , jobs [i ].start , profit , i - 1 );
31
+ profit [i ] = Math .max (profit [i - 1 ], lastMaxSum + jobs [i ].profit );
32
+ }
33
+
34
+ return profit [profit .length - 1 ];
35
+ }
36
+
37
+ private int foundMaxProfitBeforeStart (Job [] jobs , int time , int [] profit , int right ) {
38
+ if (jobs .length < 60 ) {
39
+ return foundMaxProfitBeforeStart1 (jobs , time , profit , right );
40
+ } else {
41
+ return foundMaxProfitBeforeStart2 (jobs , time , profit , right );
42
+ }
43
+ }
44
+
45
+ private int foundMaxProfitBeforeStart1 (Job [] jobs , int time , int [] profit , int right ) {
46
+ for (int i = right ; i >= 0 ; i --) {
47
+ if (jobs [i ].end <= time ) {
48
+ return profit [i ];
49
+ }
50
+ }
51
+ return 0 ;
52
+ }
53
+
54
+ private int foundMaxProfitBeforeStart2 (Job [] jobs , int time , int [] profit , int right ) {
55
+ int left = 0 ;
56
+ while (left < right ) {
57
+ int mid = (left + right ) / 2 ;
58
+
59
+ if (jobs [mid ].end > time ) {
60
+ right = mid - 1 ;
61
+ } else {
62
+ if (mid == right || jobs [mid + 1 ].end > time ) {
63
+ return profit [mid ];
64
+ } else {
65
+ left = mid + 1 ;
66
+ }
67
+ }
68
+ }
69
+ // left 不会超出边界,所以从left出发计算比较方便
70
+ if (jobs [left ].end > time ) {
71
+ left = left - 1 ;
72
+ }
73
+ return left == -1 ? 0 : profit [left ];
74
+ }
75
+ }
0 commit comments