Time Needed to Buy Tickets

easy array queue simulation

Problem

Each step the first person buys one ticket then goes to the back unless done. Return the time (in steps) until person at index k buys all their tickets.

Inputtickets = [2, 3, 2], k = 2
Output6
Ahead (idx < k) buy at most t[k]; behind at most t[k]−1.

def time_required_to_buy(tickets, k):
    total = 0
    for i, t in enumerate(tickets):
        if i <= k:
            total += min(t, tickets[k])
        else:
            total += min(t, tickets[k] - 1)
    return total
function timeRequiredToBuy(tickets, k) {
  let total = 0;
  for (let i = 0; i < tickets.length; i++) {
    if (i <= k) total += Math.min(tickets[i], tickets[k]);
    else total += Math.min(tickets[i], tickets[k] - 1);
  }
  return total;
}
class Solution {
    public int timeRequiredToBuy(int[] tickets, int k) {
        int total = 0;
        for (int i = 0; i < tickets.length; i++) {
            if (i <= k) total += Math.min(tickets[i], tickets[k]);
            else total += Math.min(tickets[i], tickets[k] - 1);
        }
        return total;
    }
}
int timeRequiredToBuy(vector<int>& tickets, int k) {
    int total = 0;
    for (int i = 0; i < (int)tickets.size(); i++) {
        if (i <= k) total += min(tickets[i], tickets[k]);
        else total += min(tickets[i], tickets[k] - 1);
    }
    return total;
}
Time: O(n) Space: O(1)