Problem summary:
Each person in line has tickets[i] tickets to buy. Every second
The person at the front buys one ticket.
If they still need more tickets, they move to the end of the queue.
We need to find how many seconds it takes for the person at index k to finish buying their tickets.
My code:
public int timeRequiredToBuy(int[] tickets, int k) {
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < tickets.length; i++) {
queue.add(i);
}
int time = 0;
while (!queue.isEmpty()) {
int person = queue.poll();
if (!queue.isEmpty()) {
tickets[queue.peek()]--;
} else {
tickets[person]--;
}
time++;
if (tickets[person] > 0) {
queue.add(person);
}
if (person == k && tickets[person] == 0) {
break;
}
}
return time;
}
tickets =
[83,86,38,31,59,25,89,71,54,71,84]
k =1
Output
688
Expected
687
Why does this logic result in a value that is higher than the expected one? How would I correctly track the tickets for each person without accidentally decrementing the wrong one?