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?- A. 3
- B. 5
- C. 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
- Problem: How many decimal digits does 100! have? Run the code. python import math print(len(str(math.factorial(100)))) What is printed?
- Problem: What is the digit sum of 100!? Run the code. python import math print(sum(int(c) for c in str(math.factorial(100)))) What is…
- Problem: Longest path in a weighted DAG from vertex 0 with edges 0->1 (3), 1->2 (4), 0->2 (10). Run the DP over the topological order…
- Problem: How many ordered sequences of jumps of sizes 2, 3 or 5 sum exactly to 12? Run the DP. python ways = [1] + [0] 12 for v in…
- Problem: What is the size of the largest divisible subset of [1, 2, 4, 8, 3] (every pair must satisfy one dividing the other)? Run the…
- Problem: How many subarrays of [1, 2, 1, 2, 3] contain exactly 2 distinct values? Run the code using the 'at most' trick. python from…