C++ || O(n) and O(1) TIME AND SPACE || Apr 9 2024 Daily
Intuition\nThe problem seems to require simulating the process of people buying tickets in a queue. Each person buys tickets one by one, and if they run out of 
# Intuition\nThe problem seems to require simulating the process of people buying tickets in a queue. Each person buys tickets one by one, and if they run out of tickets to buy, they leave the line. We need to find out how much time it takes for the person at position k to finish buying tickets.\n\n# Approach\n- We iterate through the people in the queue.\n- For each person, if their position is before or equal to k, they buy the minimum of their required tickets and the tickets that the person at position k wants.\n- If the person\'s position is after k, they buy the minimum of their required tickets and one less than the tickets that the person at position k wants (since the person at position k has already bought some tickets).\n- We accumulate the time taken for each person to buy their tickets.\n\n# Complexity\n- Time complexity:\nThe time complexity of the solution is O(n), where n is the number of people in the queue. We iterate through the queue once to calculate the time taken for each person to buy tickets.\n\n- Space complexity:\nThe space complexity is O(1) because we only use a constant amount of extra space regardless of the input size. The space used for variables such as `ans`, `i`, and `k` is fixed and doesn\'t depend on the number of people in the queue.\n\n\n# Code\n```\nclass Solution {\n public:\n  int timeRequiredToBuy(vector<int>& tickets, int k) {\n    int ans = 0;\n\n    for (int i = 0; i < tickets.size(); ++i)\n      if (i <= k)\n        ans += min(tickets[i], tickets[k]);\n      else\n        ans += min(tickets[i], tickets[k] - 1);\n\n    return ans;\n  }\n};\n```
['Array', 'Queue', 'Simulation', 'C++']