Sponsored
Sponsored
This approach uses dynamic programming to maintain a cost array where each cell represents the minimum cost to travel up to that day. For each travel day, you decide to either buy a 1-day, 7-day, or 30-day pass and record the cost accordingly.
Time Complexity: O(n) where n is the last travel day. Space Complexity: O(n) for the DP array.
1function mincostTickets(days, costs) {
2 let lastDay = days[days.length - 1];
3 let dp = new Array(lastDay + 1).fill(0);
4 let dayIndex = new Set(days);
5 for (let i = 1; i <= lastDay; i++) {
6 if (!dayIndex.has(i)) {
7 dp[i] = dp[i - 1];
8 } else {
9 dp[i] = Math.min(
10 dp[i - 1] + costs[0],
11 (dp[i - 7] || 0) + costs[1],
12 (dp[i - 30] || 0) + costs[2]
13 );
14 }
15 }
16 return dp[lastDay];
17}
18
19console.log(mincostTickets([1,4,6,7,8,20], [2,7,15])); // Output: 11
The JavaScript implementation follows a similar pattern to other dynamic programming solutions, tracking the minimum cost up to the last travel day. It uses, Map to quickly determine travel days and handles each travel day dynamically by checking the cost using 1, 7, or 30 day passes.
This approach uses recursion with memoization to explore each travel day recursively, storing intermediate results to avoid redundant calculations. It offers a top-down perspective on decision-making for ticket purchasing.
Time Complexity: O(n) where n is the number of travel days due to memoization. Space Complexity: O(n) for the memo array.
1using System.Collections.Generic;
public class Solution {
private int[] days;
private int[] costs;
private int[] memo;
public int MincostTickets(int[] days, int[] costs) {
this.days = days;
this.costs = costs;
this.memo = new int[days.Length];
Array.Fill(memo, -1);
return Dfs(0);
}
private int Dfs(int i) {
if (i >= days.Length) return 0;
if (memo[i] != -1) return memo[i];
int oneDay = costs[0] + Dfs(i + 1);
int j = i;
while (j < days.Length && days[j] < days[i] + 7) j++;
int sevenDay = costs[1] + Dfs(j);
while (j < days.Length && days[j] < days[i] + 30) j++;
int thirtyDay = costs[2] + Dfs(j);
return memo[i] = Math.Min(oneDay, Math.Min(sevenDay, thirtyDay));
}
}
C# implements the same recursive logic with memoization as seen in other languages, preserving previously computed costs for successive travel days for faster computations. It methodically examines each day to be covered by these various ticket options.