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;
    }
    };

相关推荐
打码的老程是远篁4 分钟前
手把手教你玩转大模型——3. Transformer 的位置编码——模型怎么知道谁在前,谁在后?
人工智能·算法
嘎嘎风5 分钟前
MiniMind 学习笔记之 06 一张图、一百行:MiniMind 的骨架
算法·源码
用户7341681035488 分钟前
只盯被动响应做状态监测?论“控制信号”在变工况故障诊断中的重要作用
算法
Ivanqhz11 分钟前
MQA、GQA、稀疏/滑动窗口注意力及混合范式
人工智能·算法·机器学习
罗湖老棍子19 分钟前
荒岛野人(信息学奥赛一本通- P1637)(洛谷-P2421)
算法·数论·枚举·裴蜀定理·扩展欧几里得·扩展中国剩余定理
朝朝辞暮i24 分钟前
C++ 第 40 章:ROS2 Publisher + Timer + Subscriber + Callback + Executor 完整闭环
开发语言·c++·算法·ros2
400分31 分钟前
具身智能系列之从零到「机械臂会放试管」:π0.5 VLA 真机部署完全指南【第一节】
算法
小宋102141 分钟前
一套服务托管多个 LoRA:适配器加载、租户隔离与热切换实战
大数据·人工智能·算法
Rosanci1 小时前
Codex 下载与本地部署实战:从安装到运行全流程指南
开发语言·前端·算法·chatgpt·codex
我爱工作&工作love我1 小时前
P14358 [CSP-J 2025] 座位
算法