We can simulate the ticket buying process exactly as described. People stand in a queue, and each person buys one ticket at a time before going to the back of the line. We continue this process until the person at position k has bought all their tickets.
Using a queue data structure naturally models this behavior. We track each person's index and decrement their remaining tickets each time they reach the front. When someone finishes buying all their tickets, they leave the queue. The simulation ends when the person at index k completes their purchase.
0 to n-1 representing each person's position.0.time by 1.0 and their index equals k, return the current time.class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
n = len(tickets)
q = deque()
for i in range(n):
q.append(i)
time = 0
while q:
time += 1
cur = q.popleft()
tickets[cur] -= 1
if tickets[cur] == 0:
if cur == k:
return time
else:
q.append(cur)
return timeWhere is the size of the input array and is the maximum value in the input array.
Instead of using a queue, we can simulate the process by iterating through the array in a circular manner. We keep a pointer that cycles through positions 0, 1, 2, ..., n-1, 0, 1, ... and skip anyone who has already finished buying tickets.
This approach eliminates the need for a separate queue data structure while achieving the same simulation. We track time and decrement ticket counts as we cycle through, stopping when the person at position k finishes.
0 and time counter at 0.time and decrementing the current person's ticket count.0) and their index equals k, return time.idx = (idx + 1) % n.class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
n = len(tickets)
idx = 0
time = 0
while True:
time += 1
tickets[idx] -= 1
if tickets[idx] == 0:
if idx == k:
return time
idx = (idx + 1) % n
while tickets[idx] == 0:
idx = (idx + 1) % n
return timeWhere is the size of the input array and is the maximum value in the input array.
Instead of simulating the entire process, we can calculate the answer directly. Consider how many times each person will buy a ticket before person k finishes.
For people standing at or before position k, they will buy tickets at most tickets[k] times, since they get to buy before person k in each round. For people standing after position k, they will buy at most tickets[k] - 1 times, since in the final round, person k finishes before they get another turn. Each person's contribution is capped by their own ticket needs.
res to 0.0 to n-1.i <= k, add min(tickets[i], tickets[k]) to the result.i > k, add min(tickets[i], tickets[k] - 1) to the result.