문제
There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.
You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].
Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.
Return the time taken for the person at position k (0-indexed) to finish buying tickets.
n명의 사람들이 티켓을 사기 위해 줄을 서 있다.
각 사람이 사고 싶은 수의 티켓 tickets이 주어질 때 k번째 사람이 티켓을 다 구매하기 위해 걸리는 시간을 구하는 문제이다.
티켓은 한번 살 때 1초를 들여 하나만 살 수 있고, 하나를 사고나면 맨 뒤로가서 줄을 서야 한다.
Example 1:
Input: tickets = [2,3,2], k = 2
Output: 6
Explanation: - In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1]. - In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0]. The person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.
Example 2:
Input: tickets = [5,1,1,1], k = 0
Output: 8
Explanation: - In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0]. - In the next 4 passes, only the person in position 0 is buying tickets. The person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.
풀이
아이디어
k번째 사람이 티켓 x개를 사기 위해서는
앞의 사람들은 최대 x개의 티켓을 사야만하고,
뒤에 사람들은 최대 x-1개의 티켓을 사야만한다.
코드
class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
# k번째 사람이 티켓을 다 살 때까지 필요한 구매만 남기는 작업
for i, ticket in enumerate(tickets):
# 앞의 사람들은 최대 tickets[k]개의 티켓을 사야만 함
if i <= k: tickets[i] = min([ticket, tickets[k]])
# 뒤에 사람들은 최대 tickets[k]-1개의 티켓을 사야만 함
else: tickets[i] = min([ticket, tickets[k]-1])
return sum(tickets)
한 줄 코딩...
class Solution: def timeRequiredToBuy(self, tickets: List[int], k: int) -> int: return sum([min([ticket, tickets[k] - (0 if i<=k else 1)]) for i, ticket in enumerate(tickets)])
후기
난이도
이런 방식의 아이디어를 바로 떠올리긴 쉽지 않을 수 있지만,
다른 풀이방식도 존재하기 때문에 문제만 이해하면 어떻게 풀지는 쉽게 파악할 수 있다.
구현도 쉽게 할 수 있다.
다른 풀이
맨 앞의 사람을 맨 뒤로 보내며 문제 그대로 구현하여 풀 수 있다.
'Algorithm' 카테고리의 다른 글
[LeetCode] 402. Remove K Digits (Daily Question) (0) | 2024.04.11 |
---|---|
[LeetCode] 950. Reveal Cards In Increasing Order (Daily Question) (0) | 2024.04.10 |
[LeetCode] 1700. Number of Students Unable to Eat Lunch (Daily Question) (0) | 2024.04.08 |
[LeetCode] 678. Valid Parenthesis String (Daily Question) (0) | 2024.04.07 |
[LeetCode] 1249. Minimum Remove to Make Valid Parentheses (Daily Question) (0) | 2024.04.06 |