|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive function to calculate the minimum cost using memoization |
| 4 | + int solve(vector<int>& days, vector<int>& costs, int n, int index, vector<int>& dp) { |
| 5 | + // Base case: if the index is out of bounds, no cost is required |
| 6 | + if (index >= n) |
| 7 | + return 0; |
| 8 | + |
| 9 | + // If the result is already computed for the current index, return it (memoization) |
| 10 | + if (dp[index] != -1) |
| 11 | + return dp[index]; |
| 12 | + |
| 13 | + // **Cost for a 1-day pass**: |
| 14 | + // Move to the next day and add the cost of a 1-day pass |
| 15 | + int cost1 = solve(days, costs, n, index + 1, dp) + costs[0]; |
| 16 | + |
| 17 | + // **Cost for a 7-day pass**: |
| 18 | + // Find the first day not covered by the 7-day pass (days[index] + 7) |
| 19 | + int i; |
| 20 | + for (i = index; i < n && days[i] < days[index] + 7; i++); |
| 21 | + // Recursively calculate the cost from that day and add the cost of a 7-day pass |
| 22 | + int cost7 = solve(days, costs, n, i, dp) + costs[1]; |
| 23 | + |
| 24 | + // **Cost for a 30-day pass**: |
| 25 | + // Find the first day not covered by the 30-day pass (days[index] + 30) |
| 26 | + for (i = index; i < n && days[i] < days[index] + 30; i++); |
| 27 | + // Recursively calculate the cost from that day and add the cost of a 30-day pass |
| 28 | + int cost30 = solve(days, costs, n, i, dp) + costs[2]; |
| 29 | + |
| 30 | + // Store the minimum cost for the current index in the memoization table |
| 31 | + dp[index] = min(cost1, min(cost7, cost30)); |
| 32 | + |
| 33 | + // Return the computed minimum cost for the current index |
| 34 | + return dp[index]; |
| 35 | + } |
| 36 | + |
| 37 | + // Main function to calculate the minimum cost of traveling |
| 38 | + int mincostTickets(vector<int>& days, vector<int>& costs) { |
| 39 | + // Create a memoization table initialized to -1 |
| 40 | + vector<int> dp(days.size() + 1, -1); |
| 41 | + // Start calculating from the first day |
| 42 | + return solve(days, costs, days.size(), 0, dp); |
| 43 | + } |
| 44 | +}; |
0 commit comments