What is Time to Buy Tickets
People stand in a queue to buy tickets. tickets[i] is how many tickets person i still needs. Each second, the person at the front buys one ticket and goes to the rear if they still need more. Return the second when person k finishes.
Approach
Visualization & algorithm
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Fast count | O(n) | Each person contributes one min(). |
| Simulation | O(sum of tickets) | Fine for a short picture, slow if every person wants many tickets. |
Implementation
def solve(self, tickets, k):
need = tickets[k]
time = 0
for i, x in enumerate(tickets):
if i <= k: time += min(x, need)
else: time += min(x, need - 1)
return time