LeetCode Solutions

983. Minimum Cost For Tickets

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  int mincostTickets(vector<int>& days, vector<int>& costs) {
    int ans = 0;
    queue<pair<int, int>> last7;
    queue<pair<int, int>> last30;

    for (int day : days) {
      while (!last7.empty() && last7.front().first + 7 <= day)
        last7.pop();
      while (!last30.empty() && last30.front().first + 30 <= day)
        last30.pop();
      last7.emplace(day, ans + costs[1]);
      last30.emplace(day, ans + costs[2]);
      ans = min({ans + costs[0], last7.front().second, last30.front().second});
    }

    return ans;
  }
};
			

class Solution {
  public int mincostTickets(int[] days, int[] costs) {
    int ans = 0;
    Queue<int[]> last7 = new ArrayDeque<>(); // [day, cost]
    Queue<int[]> last30 = new ArrayDeque<>();

    for (int day : days) {
      while (!last7.isEmpty() && last7.peek()[0] + 7 <= day)
        last7.poll();
      while (!last30.isEmpty() && last30.peek()[0] + 30 <= day)
        last30.poll();
      last7.offer(new int[] {day, ans + costs[1]});
      last30.offer(new int[] {day, ans + costs[2]});
      ans = Math.min(ans + costs[0], Math.min(last7.peek()[1], last30.peek()[1]));
    }

    return ans;
  }
}
			

class Solution:
  def mincostTickets(self, days: List[int], costs: List[int]) -> int:
    ans = 0
    last7 = deque()
    last30 = deque()

    for day in days:
      while last7 and last7[0][0] + 7 <= day:
        last7.popleft()
      while last30 and last30[0][0] + 30 <= day:
        last30.popleft()
      last7.append([day, ans + costs[1]])
      last30.append([day, ans + costs[2]])
      ans = min(ans + costs[0], last7[0][1], last30[0][1])

    return ans