We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Definitely not necessary to use dynamic programming. Can be solved in O(n log n) by creating and sorting a list of the (arrival, cook_time) pairs by arrival, then using a small min-heap, sorted by cook time, to keep track of the people who are currently in the pizza shop (i.e. whose arrival time < the total time elapsed) by using the list as a stack. This is O(n log n + n log p) time where p is the number of people in the shop at any given time, and since p <= n, the algorithm is O(n log n). Here is the code:
from heapq import heappush, heappop
tasks = []
N = int(input())
for _ in range(N):
arrival, cook_time = map(int, input().split())
tasks.append((arrival, cook_time))
tasks.sort(reverse=True)
pq = []
time_waiting = 0
current_time = 0
while tasks or pq:
while tasks and tasks[-1][0] <= current_time:
heappush(pq, tasks.pop()[::-1])
if pq:
current_task = heappop(pq)
current_time += current_task[0]
time_waiting += current_time - current_task[1]
else:
heappush(pq, tasks.pop()[::-1])
current_time = pq[0][1]
print(time_waiting // N)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Average Waiting Time
You are viewing a single comment's thread. Return to all comments →
Definitely not necessary to use dynamic programming. Can be solved in O(n log n) by creating and sorting a list of the (arrival, cook_time) pairs by arrival, then using a small min-heap, sorted by cook time, to keep track of the people who are currently in the pizza shop (i.e. whose arrival time < the total time elapsed) by using the list as a stack. This is O(n log n + n log p) time where p is the number of people in the shop at any given time, and since p <= n, the algorithm is O(n log n). Here is the code: