Skip to content

Commit 75cefab

Browse files
authored
Update Buy the Ticket
1 parent 62349fb commit 75cefab

File tree

1 file changed

+37
-0
lines changed
  • Course 2 - Data Structures in JAVA/Lecture 21 - Priority Queues II

1 file changed

+37
-0
lines changed

Course 2 - Data Structures in JAVA/Lecture 21 - Priority Queues II/Buy the Ticket

+37
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,40 @@ Sample Output 2 :
4141
4
4242
*/
4343

44+
import java.util.*;
45+
public class Solution {
46+
47+
public static int buyTicket(int input[], int k) {
48+
/* Your class should be named Solution
49+
* Don't write main().
50+
* Don't read input, it is passed as function argument.
51+
* Return output and don't print it.
52+
* Taking input and printing output is handled automatically.
53+
*/
54+
Queue<Integer> queue = new LinkedList<>();
55+
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
56+
for (int i=0;i<input.length;i++){
57+
queue.add(i);
58+
pq.add(input[i]);
59+
}
60+
int time=0;
61+
while (!queue.isEmpty()){
62+
if (input[queue.peek()] < pq.peek())
63+
{
64+
queue.add(queue.poll());
65+
}
66+
else
67+
{
68+
int idx = queue.poll();
69+
pq.remove();
70+
time++;
71+
if (idx == k)
72+
{
73+
break;
74+
}
75+
}
76+
}
77+
return time;
78+
79+
}
80+
}

0 commit comments

Comments
 (0)