|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + int mincostTickets(vector<int>& days, vector<int>& costs) { |
| 4 | + int ans = 0; // Variable to keep track of the minimum cost so far |
| 5 | + |
| 6 | + // Queues to track the minimum cost for 7-day and 30-day passes |
| 7 | + queue<pair<int, int>> month; // Stores {day, cost} for the 30-day pass |
| 8 | + queue<pair<int, int>> week; // Stores {day, cost} for the 7-day pass |
| 9 | + |
| 10 | + // Iterate through all the travel days |
| 11 | + for (int day : days) { |
| 12 | + // Remove outdated entries from the month queue |
| 13 | + // If the current day is greater than or equal to the day of the oldest entry + 30, |
| 14 | + // it means the 30-day pass for that day is no longer valid |
| 15 | + while (!month.empty() && month.front().first + 30 <= day) { |
| 16 | + month.pop(); |
| 17 | + } |
| 18 | + |
| 19 | + // Remove outdated entries from the week queue |
| 20 | + // If the current day is greater than or equal to the day of the oldest entry + 7, |
| 21 | + // it means the 7-day pass for that day is no longer valid |
| 22 | + while (!week.empty() && week.front().first + 7 <= day) { |
| 23 | + week.pop(); |
| 24 | + } |
| 25 | + |
| 26 | + // Add a new entry for the current day to the week queue |
| 27 | + // This represents the cost of buying a 7-day pass starting today |
| 28 | + week.push(make_pair(day, ans + costs[1])); |
| 29 | + |
| 30 | + // Add a new entry for the current day to the month queue |
| 31 | + // This represents the cost of buying a 30-day pass starting today |
| 32 | + month.push(make_pair(day, ans + costs[2])); |
| 33 | + |
| 34 | + // Update the minimum cost (ans) for the current day |
| 35 | + // Consider three options: |
| 36 | + // 1. Buying a 1-day pass for the current day |
| 37 | + // 2. Using the cheapest cost from the week queue |
| 38 | + // 3. Using the cheapest cost from the month queue |
| 39 | + ans = min(ans + costs[0], min(week.front().second, month.front().second)); |
| 40 | + } |
| 41 | + |
| 42 | + // Return the total minimum cost to cover all the travel days |
| 43 | + return ans; |
| 44 | + } |
| 45 | +}; |
0 commit comments