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.
1using System.Collections.Generic;
public class Solution {
public int MincostTickets(int[] days, int[] costs) {
var travelDays = new HashSet<int>(days);
int[] dp = new int[366];
for (int i = 1; i <= 365; i++) {
if (!travelDays.Contains(i)) {
dp[i] = dp[i - 1];
} else {
dp[i] = Math.Min(
dp[i - 1] + costs[0],
Math.Min(dp[Math.Max(0, i - 7)] + costs[1],
dp[Math.Max(0, i - 30)] + costs[2])
);
}
}
return dp[365];
}
}
The C# solution mirrors the logic seen in Python and Java, utilizing HashSet for efficient travel day checks and structuring the DP array to accumulate the minimum cost to each successive day.
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;
2using System.Collections.Generic;
3
4public class Solution {
5 private int[] days;
6 private int[] costs;
7 private int[] memo;
8
9 public int MincostTickets(int[] days, int[] costs) {
10 this.days = days;
11 this.costs = costs;
12 this.memo = new int[days.Length];
13 Array.Fill(memo, -1);
14 return Dfs(0);
15 }
16
17 private int Dfs(int i) {
18 if (i >= days.Length) return 0;
19 if (memo[i] != -1) return memo[i];
20
21 int oneDay = costs[0] + Dfs(i + 1);
22 int j = i;
23 while (j < days.Length && days[j] < days[i] + 7) j++;
24 int sevenDay = costs[1] + Dfs(j);
25 while (j < days.Length && days[j] < days[i] + 30) j++;
26 int thirtyDay = costs[2] + Dfs(j);
27
28 return memo[i] = Math.Min(oneDay, Math.Min(sevenDay, thirtyDay));
29 }
30}
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.
Solve with full IDE support and test cases