Python Algorithms - Greedy - "Muji's Mukbang Live"

Sunmi Shin·2022년 11월 5일

Python Algorithms

목록 보기
2/7
post-thumbnail

Problem:
Which food number does Muji have to restart to eat, when a network disconnection happens?
무지가 먹방 라이브 도중 네트워크 장애가 발생하면 재시작을 위해 먹어야할 음식의 번호는 무엇인가?

Rules:

  1. Muji starts to eat food #1, and the rotate disk brings food to Muji in increasing order.
  2. When Muji eats the last # of food, the disk brings #1 again.
  3. It allows 1 second for one bite of food, and because the disk rotates at every second, Muji has to eat the next food with the eaten food being left.
  4. It takes no time to bring the food for the disk.

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_timeskresult
[3, 1, 2]51
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]
profile
Tempest Data Analyst

0개의 댓글