forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourseScheduleIII.java
39 lines (31 loc) · 1.04 KB
/
CourseScheduleIII.java
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
class Solution {
// TC : O(nlogn)
// SC : O(n)
public int scheduleCourse(int[][] courses) {
Arrays.sort(courses, (a,b) -> (a[1] - b[1]));
// Course duration of the selected ones
PriorityQueue<Integer> pq = new PriorityQueue<Integer> ((a,b) -> (b-a));
int timeElapsed = 0;
for(int[] course : courses){
if(timeElapsed + course[0] <= course[1]){
pq.offer(course[0]);
timeElapsed += course[0];
} else if(!pq.isEmpty() && pq.peek() > course[0]){
timeElapsed = timeElapsed - pq.poll();
pq.offer(course[0]);
timeElapsed = timeElapsed + course[0];
} else {
// pq.peek() < course[0]
// reject the current course
}
}
return pq.size(); // 3
}
// [100,200],[200,1300],[1000,1250],[2000,3200]]
//[100, 200]
//[1000, 1250]
//[200, 1300]
//[2000 3200]
// timeElapsed = 1100 + 200 = 1300
// pq {100 , 1000, 200}
}