2073.买票需要的时间

https://leetcode-cn.com/problems/time-needed-to-buy-tickets/

观察法

对k及k之前的每个人i,若i买的票比k少,则i要的票一定能被满足;否则i最多能买到和k一样多的票

对k之后的每个人i,若i买的票大于等于k,则最多能满足tickets[k] - 1(因为k被满足后就结束了);否则i要的票能被满足

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

最后更新于