Course Schedule III

hard heap greedy

Problem

Each course has (duration, lastDay). Maximize the number you can finish.

Inputcourses=[[100,200],[200,1300],[1000,1250],[2000,3200]]
Output3
Drop the 1000-long course; keep 100+200+2000 = 2300 ≤ 3200.

def schedule_courses(courses):
    import heapq
    courses.sort(key=lambda c: c[1])
    h, t = [], 0
    for d, end in courses:
        heapq.heappush(h, -d); t += d
        if t > end: t += heapq.heappop(h)
    return len(h)
function scheduleCourses(courses) {
  courses.sort((a, b) => a[1] - b[1]);
  const h = []; let t = 0;
  const up = i => { while (i && h[(i-1)>>1] < h[i]) { [h[i], h[(i-1)>>1]] = [h[(i-1)>>1], h[i]]; i = (i-1)>>1; } };
  const down = i => { while (true) { let l = i*2+1, r = i*2+2, m = i; if (l < h.length && h[l] > h[m]) m = l; if (r < h.length && h[r] > h[m]) m = r; if (m === i) break; [h[i], h[m]] = [h[m], h[i]]; i = m; } };
  for (const [d, e] of courses) {
    h.push(d); up(h.length - 1); t += d;
    if (t > e) { t -= h[0]; h[0] = h[h.length-1]; h.pop(); down(0); }
  }
  return h.length;
}
int scheduleCourse(int[][] courses) {
    Arrays.sort(courses, (a, b) -> a[1] - b[1]);
    PriorityQueue pq = new PriorityQueue<>(Comparator.reverseOrder());
    int t = 0;
    for (int[] c : courses) {
        pq.offer(c[0]); t += c[0];
        if (t > c[1]) t -= pq.poll();
    }
    return pq.size();
}
int scheduleCourse(vector>& courses) {
    sort(courses.begin(), courses.end(), [](auto& a, auto& b){ return a[1] < b[1]; });
    priority_queue pq; int t = 0;
    for (auto& c : courses) {
        pq.push(c[0]); t += c[0];
        if (t > c[1]) { t -= pq.top(); pq.pop(); }
    }
    return pq.size();
}
Time: O(n log n) Space: O(n)