Data Structures & AlgorithmsVery hardProduct Company SDE · greedy heap round

Problem: Maximum number of events attended when each event is [start, end] (day-inclusive) and you can attend one event per day. Events are [[1,4],[4,4],[2,2],[3,4],[1,1]]. Run the greedy heap code.

Problem: Maximum number of events attended when each event is [start, end] (day-inclusive) and you can attend one event per day. Events are [[1,4],[4,4],[2,2],[3,4],[1,1]]. Run the greedy heap code.
import heapq
ev = sorted([[1, 4], [4, 4], [2, 2], [3, 4], [1, 1]])
h = []
i = 0
res = 0
day = 1
while i < len(ev) or h:
    if not h and i < len(ev) and ev[i][0] > day:
        day = ev[i][0]
    while i < len(ev) and ev[i][0] <= day:
        heapq.heappush(h, ev[i][1])
        i += 1
    while h and h[0] < day:
        heapq.heappop(h)
    if h:
        heapq.heappop(h)
        res += 1
    day += 1
print(res)
What is printed?
  1. A. 3
  2. B. 5
  3. C. 4
  4. D. 2

Correct answer: C. 4

Day 1 takes [1,1], day 2 takes [2,2], day 3 takes [3,4] and day 4 takes [4,4]. All four days are used, so 4 is optimal.

More Coding Interview Problems questions

Exams that ask this topic