630. Course Schedule III
Problem
courses[i] = [duration, lastDay]: the course takes duration consecutive days and must be finished by day lastDay. You take one course at a time, starting on day 1. Return the maximum number of courses you can complete.
Example: [[100,200],[200,1300],[1000,1250],[2000,3200]] → 3
Constraints: up to 10⁴ courses.
Sort by deadline and take courses greedily, tracking total time. If the deadline is exceeded, drop the longest course taken so far (max-heap): the count stays the same but the time used shrinks.
Complexity: O(n log n).
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
h, t = [], 0
for dur, last in sorted(courses, key=lambda c: c[1]):
heappush(h, -dur)
t += dur
if t > last:
t += heappop(h) # remove the longest (stored negative)
return len(h)
assert Solution().scheduleCourse([[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]) == 3
assert Solution().scheduleCourse([[1, 2]]) == 1
assert Solution().scheduleCourse([[3, 2], [4, 3]]) == 0
class Solution {
public int scheduleCourse(int[][] courses) {
Arrays.sort(courses, (a, b) -> a[1] - b[1]);
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
int t = 0;
for (int[] c : courses) {
pq.add(c[0]);
t += c[0];
if (t > c[1]) t -= pq.poll();
}
return pq.size();
}
}
type MaxHeap []int
func (h MaxHeap) Len() int { return len(h) }
func (h MaxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *MaxHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func scheduleCourse(courses [][]int) int {
sort.Slice(courses, func(i, j int) bool { return courses[i][1] < courses[j][1] }) // by deadline
h, t := &MaxHeap{}, 0
for _, c := range courses {
heap.Push(h, c[0])
t += c[0]
if t > c[1] { // over the deadline: drop the longest course taken
t -= heap.Pop(h).(int)
}
}
return h.Len()
}