## Problem Statement

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

```
Input: tickets = [2,3,2], k = 2
Output: 6
Explanation:
- 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

```
Input: tickets = [5,1,1,1], k = 0
Output: 8
Explanation:
- 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.
```

Try here before watching the video.

### Video Solution

### Java Code

```
class Solution {
public int timeRequiredToBuy(int[] tickets, int k) {
int time = 0;
for(int i = 0; i < tickets.length; i++) {
if(i <= k) {
time += Math.min(tickets[i], tickets[k]);
} else {
time += Math.min(tickets[i], tickets[k] - 1);
}
}
return time;
}
}
```

### C++ Code

```
class Solution {
public:
int timeRequiredToBuy(vector<int>& tickets, int k) {
int time = 0;
for (int i = 0; i < tickets.size(); i++) {
if (i <= k) {
time += std::min(tickets[i], tickets[k]);
} else {
time += std::min(tickets[i], tickets[k] - 1);
}
}
return time;
}
};
```

### Python Code

```
class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
time = 0
for i in range(len(tickets)):
if i <= k:
time += min(tickets[i], tickets[k])
else:
time += min(tickets[i], tickets[k] - 1)
return time
```

### Javascript Code

```
/**
* @param {number[]} tickets
* @param {number} k
* @return {number}
*/
var timeRequiredToBuy = function(tickets, k) {
let time = 0;
for (let i = 0; i < tickets.length; i++) {
if (i <= k) {
time += Math.min(tickets[i], tickets[k]);
} else {
time += Math.min(tickets[i], tickets[k] - 1);
}
}
return time;
};
```

### Go Code

```
func timeRequiredToBuy(tickets []int, k int) int {
time := 0
for i := 0; i < len(tickets); i++ {
if i <= k {
time += min(tickets[i], tickets[k])
} else {
time += min(tickets[i], tickets[k]-1)
}
}
return time
}
```

Time Complexity : O(n)

Space Complexity : O(1)