-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path30_Kth_tickets.cpp
More file actions
97 lines (63 loc) · 2.78 KB
/
30_Kth_tickets.cpp
File metadata and controls
97 lines (63 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.
// You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].
// Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.
// Return the time taken for the person initially at position k (0-indexed) to finish buying tickets.
// Example 1:
// Input: tickets = [2,3,2], k = 2
// Output: 6
// Explanation:
// The queue starts as [2,3,2], where the kth person is underlined.
// After the person at the front has bought a ticket, the queue becomes [3,2,1] at 1 second.
// Continuing this process, the queue becomes [2,1,2] at 2 seconds.
// Continuing this process, the queue becomes [1,2,1] at 3 seconds.
// Continuing this process, the queue becomes [2,1] at 4 seconds. Note: the person at the front left the queue.
// Continuing this process, the queue becomes [1,1] at 5 seconds.
// Continuing this process, the queue becomes [1] at 6 seconds. The kth person has bought all their tickets, so return 6.
// Example 2:
// Input: tickets = [5,1,1,1], k = 0
// Output: 8
// Explanation:
// The queue starts as [5,1,1,1], where the kth person is underlined.
// After the person at the front has bought a ticket, the queue becomes [1,1,1,4] at 1 second.
// Continuing this process for 3 seconds, the queue becomes [4] at 4 seconds.
// Continuing this process for 4 seconds, the queue becomes [] at 8 seconds. The kth person has bought all their tickets, so return 8.
// My solution but not optimal
class Solution {
public:
int timeRequiredToBuy(vector<int>& tickets, int k) {
queue<pair<int,int>> q;
for(int i=0;i<tickets.size();i++){
q.push({tickets[i],i});
}
int time=0;
while(!q.empty()){
auto[t,idx]=q.front();
q.pop();
time++;
t--;
if(t>0){
q.push({t,idx});
}
if(idx==k && t==0){
return time;
}
}
return time;
}
};
// optimal solution
class Solution {
public:
int timeRequiredToBuy(vector<int>& tickets, int k) {
int n=tickets.size();
int cnt=0,i=0;
while(tickets[k]>0){
if(tickets[i]>0){
tickets[i]--;
cnt++;
}
i=(i+1)%n;
}
return cnt;
}
};