Sponsored
Sponsored
This approach simulates the process of each person buying their tickets. We keep track of the time spent and decrement the ticket count from each person one at a time until the k-th person has purchased all their tickets.
Time Complexity: O(n * max(tickets)) where max(tickets) is the maximum tickets any person wants to buy.
Space Complexity: O(1)
1function timeToBuyTickets(tickets, k) {
2 let time = 0;
3 const n = tickets.length;
4 while (true) {
5 for (let i = 0; i < n; i++) {
6 if (tickets[i] > 0) {
7 tickets[i]--;
8 time++;
9 if (i === k && tickets[k] === 0) return time;
10 }
11 }
12 }
13}
14
15console.log(timeToBuyTickets([2, 3, 2], 2));
JavaScript leverages the dynamic nature of arrays and uses a tactical loop to decrement ticket counts and track the time until the k-th person is done buying.
This approach avoids the simulation by calculating the total time taken mathematically. For this, we traverse through each person and calculate the time based on the number of people in the queue and the minimum value between their current tickets and the tickets needed by k-th person.
Time Complexity: O(n)
Space Complexity: O(1)
1
class TicketBuying {
public static int TimeToBuyTickets(int[] tickets, int k) {
int time = 0;
for (int i = 0; i < tickets.Length; i++) {
time += i <= k ? Math.Min(tickets[i], tickets[k]) : Math.Min(tickets[i], tickets[k] - 1);
}
return time;
}
static void Main() {
int[] tickets = {5, 1, 1, 1};
int k = 0;
Console.WriteLine("Time taken: " + TimeToBuyTickets(tickets, k));
}
}
C# version effectively calculates the same logic by iterating through the array and figuring out the purchase time based on positions and ticket requirements.