## Table of Contents

## Description: Time Needed to Buy Tickets

There are `n`

people in a line queuing to buy tickets, where the `0`

person is at the ^{th}**front** of the line and the `(n - 1)`

person is at the ^{th}**back** of the line.

You are given a **0-indexed** integer array `tickets`

of length `n`

where the number of tickets that the `i`

person would like to buy is ^{th}`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 at position *

`k`

*(0-indexed)**to finish buying tickets*.

**Example 1**

1 2 3 4 5 6 |
<strong>Input:</strong> tickets = [2,3,2], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> - In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1]. - In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0]. The person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds. |

**Example 2**

1 2 3 4 5 6 |
<strong>Input:</strong> tickets = [5,1,1,1], k = 0 <strong>Output:</strong> 8 <strong>Explanation:</strong> - In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0]. - In the next 4 passes, only the person in position 0 is buying tickets. The person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds. |

**Constraints**

`n == tickets.length`

`1 <= n <= 100`

`1 <= tickets[i] <= 100`

`0 <= k < n`

## Solution 1

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Solution { //Brute Force public int timeRequiredToBuy(int[] tickets, int k) { int count = 0; //iterate over the tickets until tickets[k] == 0 while(tickets[k]>0){ for(int i=0;i<tickets.length;i++){ if(tickets[i]>0){ tickets[i]--; count++; } if(tickets[k]==0){ break; } } } return count; } } |

### Time Complexity

O(n^2)

### Space Complexity

O(1)

## Solution 2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Solution { public int timeRequiredToBuy(int[] tickets, int k) { int a = tickets[k]; int count = 0; for(int i=0;i<tickets.length;i++){ if(i > k) //if tickets[i] > tickets[k], tickets[k] will be exhausted before tickets[i] count += Math.min(tickets[i], tickets[k]-1); } else{ count += Math.min(tickets[i], tickets[k]); } } return count; } } |

### Time Complexity

O(n)

### Space Complexity

O(1)