KatInterview

Pick One Day Per Workshop Within Its Availability Window

Greedy & IntervalsAuto-graded · 20 test cases
MediumAuto-gradedGreedy & Intervalsgreedyheapintervals

Last updated

Choose a distinct day for as many workshops as possible, each within its own window, using an earliest-deadline-first greedy with a min-heap.

Workshop Scheduling

You are given a list of workshops. Each workshop is described by a pair [open_day, close_day], the first and last day on which it can be attended (both inclusive).

Attending a workshop takes exactly one day. You may choose any single day d with open_day <= d <= close_day to attend it. You can attend at most one workshop per day, and each workshop can be attended at most once.

Return the maximum number of workshops you can attend.

Function

Implement max_workshops(windows), where windows is a list of [open_day, close_day] pairs. It returns an integer.

Clarifications

  • Attending a workshop does not occupy its whole window. It only uses the one day you pick inside the window.
  • Several workshops may share the same window, or even the same single day. Only one of them can use any given day.
  • Days are positive integers. You may choose any day in a window, so days with no workshops are simply unused.
  • The order of the input list carries no meaning.

Constraints

  • 1 <= len(windows) <= 10^5
  • windows[i] = [open_day, close_day]
  • 1 <= open_day <= close_day <= 10^5

Examples

Example 1

Input: max_workshops([[1, 2], [2, 3], [3, 4]])

Output: 3

Example 2

Input: max_workshops([[1, 2], [1, 2], [1, 2]])

Output: 2

Example 3

Input: max_workshops([[1, 1], [1, 1], [2, 2]])

Output: 2

Hints

Hint 1

Think day by day. On a given day, several workshops may be available. Which one is the most urgent to attend right now?

Hint 2

Among the workshops that have opened and not yet been attended, the one with the earliest close day has the fewest remaining chances, so attend that one first. A min-heap of close days supports this.

Hint 3

Sort windows by open day. On each day, push all newly opened workshops into the heap, discard those whose close day is before today, then pop one to attend. If the heap is empty, jump straight to the next open day instead of stepping through empty days.