|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to calculate the minimum cost using dynamic programming |
| 4 | + long long solve(vector<int>& days, vector<int>& costs, int n) { |
| 5 | + // Create a DP table to store the minimum cost for each starting day |
| 6 | + // Initialize all values to a very large number (LLONG_MAX) |
| 7 | + vector<long long> dp(n + 1, LLONG_MAX); |
| 8 | + |
| 9 | + // Base case: if there are no more days to cover, the cost is 0 |
| 10 | + dp[n] = 0; |
| 11 | + |
| 12 | + // Traverse the days array from the last travel day to the first |
| 13 | + for (int k = n - 1; k >= 0; k--) { |
| 14 | + // **Cost for a 1-day pass**: |
| 15 | + // Add the cost of a 1-day pass and move to the next day |
| 16 | + long long cost1 = dp[k + 1] + costs[0]; |
| 17 | + |
| 18 | + // **Cost for a 7-day pass**: |
| 19 | + // Find the first day not covered by the 7-day pass (days[k] + 7) |
| 20 | + int i; |
| 21 | + for (i = k; i < n && days[i] < days[k] + 7; i++); |
| 22 | + // Add the cost of a 7-day pass and use the precomputed result from dp[i] |
| 23 | + long long cost7 = dp[i] + costs[1]; |
| 24 | + |
| 25 | + // **Cost for a 30-day pass**: |
| 26 | + // Find the first day not covered by the 30-day pass (days[k] + 30) |
| 27 | + for (i = k; i < n && days[i] < days[k] + 30; i++); |
| 28 | + // Add the cost of a 30-day pass and use the precomputed result from dp[i] |
| 29 | + long long cost30 = dp[i] + costs[2]; |
| 30 | + |
| 31 | + // Store the minimum cost for day k in the DP table |
| 32 | + dp[k] = min(cost1, min(cost7, cost30)); |
| 33 | + } |
| 34 | + |
| 35 | + // Return the minimum cost starting from the first day |
| 36 | + return dp[0]; |
| 37 | + } |
| 38 | + |
| 39 | + // Main function to calculate the minimum cost of traveling |
| 40 | + int mincostTickets(vector<int>& days, vector<int>& costs) { |
| 41 | + // Call the solve function with the days, costs, and number of days |
| 42 | + return solve(days, costs, days.size()); |
| 43 | + } |
| 44 | +}; |
0 commit comments