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)
1public class TicketBuying {
2 public static int timeToBuyTickets(int[] tickets, int k) {
3 int time = 0;
4 int n = tickets.length;
5 while (true) {
6 for (int i = 0; i < n; i++) {
7 if (tickets[i] > 0) {
8 tickets[i]--;
9 time++;
10 if (i == k && tickets[k] == 0) return time;
11 }
12 }
13 }
14 }
15
16 public static void main(String[] args) {
17 int[] tickets = {2, 3, 2};
18 int k = 2;
19 System.out.println("Time taken: " + timeToBuyTickets(tickets, k));
20 }
21}
This implementation revolves around iterating over the ticket array in a loop, ensuring that each eligible person buys a ticket per cycle 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#include <vector>
#include <algorithm>
using namespace std;
int timeToBuyTickets(vector<int>& tickets, int k) {
int time = 0;
for (int i = 0; i < tickets.size(); i++) {
if (i <= k) {
time += min(tickets[i], tickets[k]);
} else {
time += min(tickets[i], tickets[k] - 1);
}
}
return time;
}
int main() {
vector<int> tickets = {5, 1, 1, 1};
int k = 0;
cout << "Time taken: " << timeToBuyTickets(tickets, k) << endl;
return 0;
}
This solution calculates the time by determining how the number of tickets each person can purchase before or after k until k finishes.