#630

Course Schedule III

Hard
ArrayGreedySortingHeap (Priority Queue)Greedy AlgorithmsHeap (Priority Queue)Sorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses a greedy approach combined with a max heap (priority queue) to efficiently manage the courses taken. By sorting the courses by their last day and using a heap to track the longest durations, we can maximize the number of courses while respecting deadlines.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the courses by their last day.
  2. 2Step 2: Initialize a max heap to keep track of the durations of the courses taken.
  3. 3Step 3: Iterate through the sorted courses, adding each course's duration to the heap if it can be completed by its last day.
  4. 4Step 4: If adding a course exceeds the current total duration, remove the longest course from the heap.
  5. 5Step 5: The size of the heap at the end gives the maximum number of courses that can be taken.
solution.py13 lines
1# Full working Python code
2import heapq
3
4def maxCourses(courses):
5    courses.sort(key=lambda x: x[1])
6    max_heap = []
7    total_duration = 0
8    for duration, last_day in courses:
9        total_duration += duration
10        heapq.heappush(max_heap, -duration)
11        if total_duration > last_day:
12            total_duration += heapq.heappop(max_heap)
13    return len(max_heap)

Complexity note: The sorting step takes O(n log n), and maintaining the heap takes O(log n) for each course, leading to an overall complexity of O(n log n).

  • 1Sorting courses by their last day allows us to make optimal decisions about which courses to take.
  • 2Using a max heap helps efficiently manage the durations of the courses taken, allowing for quick adjustments.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.