2073. Time Needed to Buy Tickets

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

Constraints:

  • n == tickets.length

  • 1 <= n <= 100

  • 1 <= tickets[i] <= 100

  • 0 <= k < n

    class Solution {
    public:
    int timeRequiredToBuy(vector& tickets, int k) {
    int n=tickets.size();
    int totalTime=0;
    queueq;
    for(int i=0;i<n;i++){
    q.push(i);
    }
    while(!q.empty() && tickets[q.front()]>0){
    int currentPerson=q.front();
    q.pop();
    tickets[currentPerson]--;
    totalTime++;
    if(tickets[currentPerson]){
    q.push(currentPerson);
    }
    if(currentPerson==k && tickets[currentPerson]==0){
    return totalTime;
    }
    }
    return totalTime;
    }
    };

相关推荐
一只齐刘海的猫2 小时前
【Leetcode】乘积最大子数组
算法·leetcode·职场和发展
余生皆假期-4 小时前
傅里叶变换和拉普拉斯变换
人工智能·算法·机器学习
不一样的故事1264 小时前
芯片设计是一个高度复杂、分工精细的系统工程
数据结构·经验分享
数模竞赛Paid answer4 小时前
2026年五一杯数学建模C题边坡预警问题求解全过程文档及程序
算法·数学建模·五一杯
梁辰兴5 小时前
软件工程:面向数据结构的设计方法
数据结构·软件工程·梁辰兴·面向数据结构的设计方法·jackson方法·warnier方法·方法比较
hold?fish:palm5 小时前
20 旋转图像
c++·算法·leetcode
NoteStream5 小时前
【C语言基础】分支和循环(上)
c语言·开发语言·c++·经验分享·笔记·算法·c#
白狐_7985 小时前
408数据结构第7章:查找②——顺序、折半、分块查找秒杀 + 真题
数据结构·算法
卷心菜的学习路6 小时前
基于多模态向量检索的数学相似题推荐系统:完整设计、算法与实验
java·python·算法·大模型·推荐算法·数学相似题
小南知更鸟6 小时前
【leetcodehot100】leetcode-hot100-20260809更新
算法·leetcode·职场和发展