LeetCode 2073 solution

LeetCode 2073 solution

problem

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 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.

python

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

중간에 0이 되어버리는 사람들은 이제 count를 해주면 안된다. 이에 대한 연산이 들어가면 154? 인가 하는 testCase에 막히게 된다. 이를 위해서 enumerate로 이전에 있는 사람들인지를 확인하고 경우의 수를 주어야한다.