
Problem:
Which food number does Muji have to restart to eat, when a network disconnection happens?
무지가 먹방 라이브 도중 네트워크 장애가 발생하면 재시작을 위해 먹어야할 음식의 번호는 무엇인가?
Rules:
The network disconnection shut down Muji's broadcasting for k seconds, and Muji wants to know which food # he has to restart to eat.
Example:
| food_times | k | result |
|---|---|---|
| [3, 1, 2] | 5 | 1 |
import heapq
def solution(food_times, k):
#if eating the all food takes longer than k, return -1
if sum(food_times) <= k:
return -1
q = []
# Put tuples, (food_times, #), into q during the loop.
for i in range(len(food_times)):
heapq.heappush(q, (food_times[i], i+1))
# Initialize the value.
sum_value = 0 #Time spent for eating the food
previous = 0 #Time spent for eating, just before
length = len(food_times) #the number of food left

# While-loop when the eating time is less equal than k seconds,
while sum_value + ((q[0][0] - previous) * length) <= k:
now = heapq.heappop(q)[0] #Current eating time
sum_value += (now - previous) * length
length -= 1 #Subtract 1 for eaten food
previous = now #reset "previous"
# Return the food # to restart eating.
result = sorted(q, key=lambda x: x[1])
return result[(k - sum_value) % length][1]