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)
1using System;
2
3class TicketBuying {
4 public static int TimeToBuyTickets(int[] tickets, int k) {
5 int time = 0;
6 int n = tickets.Length;
7 while (true) {
8 for (int i = 0; i < n; i++) {
9 if (tickets[i] > 0) {
10 tickets[i]--;
11 time++;
12 if (i == k && tickets[k] == 0) return time;
13 }
14 }
15 }
16 }
17
18 static void Main() {
19 int[] tickets = {2, 3, 2};
20 int k = 2;
21 Console.WriteLine("Time taken: " + TimeToBuyTickets(tickets, k));
22 }
23}
C# implementation uses a familiar pattern to iterate and decrement ticket counts, counting the seconds until the k-th person finishes.
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
Python's clarity helps in implementing the mathematical approach, making the calculation of each person's purchase time efficiently.