You have a queue of customers at a ticket counter represented by an array tickets
, where tickets[i]
is the number of tickets that the i-th
customer wants to buy. Each customer can buy only one ticket at a time, and they must wait until the current transaction is complete before proceeding to the next customer in a circular fashion from the start of the queue.
Return the number of seconds needed to complete the ticket buying process for the customer located at position k
.
tickets
array and the values it can contain?
1 <= tickets.length <= 1000
1 <= tickets[i] <= 1000
0 <= k < tickets.length
0
seconds.k
gets their last ticket, stop the process and return the current time.k-th
customer’s ticket count reaches 0.n
is the length of the tickets
array and m
is the maximum number of tickets any customer wants to buy. This is because, in the worst case, each customer buys a maximum of m
tickets, and we check every customer in each iteration.def timeRequiredToBuy(tickets, k):
time = 0
while tickets[k] > 0:
for i in range(len(tickets)):
if tickets[i] > 0: # If the customer still has tickets to buy
time += 1
tickets[i] -= 1
if tickets[k] == 0: # Check if the k-th customer has finished buying
return time
# Example usage
tickets = [2, 3, 2]
k = 2
print(timeRequiredToBuy(tickets, k)) # Outputs: 6
The above code tracks the total time required for the k-th
customer to buy all of their tickets. Each iteration of the loop simulates one customer buying a single ticket in a circular fashion until the process completes for the k-th
customer.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?