Skip to content

2073. Time Needed to Buy Tickets 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int timeRequiredToBuy(vector<int>& tickets, int k) {
    int ans = 0;

    for (int i = 0; i < tickets.size(); ++i)
      if (i <= k)
        ans += min(tickets[i], tickets[k]);
      else
        ans += min(tickets[i], tickets[k] - 1);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int timeRequiredToBuy(int[] tickets, int k) {
    int ans = 0;

    for (int i = 0; i < tickets.length; ++i)
      if (i <= k)
        ans += Math.min(tickets[i], tickets[k]);
      else
        ans += Math.min(tickets[i], tickets[k] - 1);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def timeRequiredToBuy(self, tickets: list[int], k: int) -> int:
    ans = 0

    for i, ticket in enumerate(tickets):
      if i <= k:
        ans += min(ticket, tickets[k])
      else:
        ans += min(ticket, tickets[k] - 1)

    return ans