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<int>& tickets, int k) {
    int n=tickets.size();
    int totalTime=0;
    queue<int>q;
    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;
    }
    };

相关推荐
BUG收容所所长16 分钟前
栈的奇妙世界:从冰棒到算法的华丽转身
前端·javascript·算法
XRZaaa22 分钟前
常见排序算法详解与C语言实现
c语言·算法·排序算法
@我漫长的孤独流浪25 分钟前
数据结构测试模拟题(4)
数据结构·c++·算法
智驱力人工智能29 分钟前
智慧零售管理中的客流统计与属性分析
人工智能·算法·边缘计算·零售·智慧零售·聚众识别·人员计数
WindSearcher2 小时前
大模型微调相关知识
后端·算法
取酒鱼食--【余九】2 小时前
rl_sar实现sim2real的整体思路
人工智能·笔记·算法·rl_sar
Magnum Lehar3 小时前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
水蓝烟雨4 小时前
[面试精选] 0094. 二叉树的中序遍历
算法·面试精选
超闻逸事4 小时前
【题解】[UTPC2024] C.Card Deck
c++·算法
暴力求解4 小时前
C++类和对象(上)
开发语言·c++·算法