DP over calendar days
Time O(365) Space O(365)dp[d] = dp[d − 1] if not travelling; otherwise min(dp[d − 1] + c0, dp[d − 7] + c1, dp[d − 30] + c2) with negative indices as 0.
days = [1,4,6,7,8,20], costs = [2,7,15]Step 1/5dp[0] = 0. Day 1 is a travel day: a 1-day pass (2) beats 7 and 15, so dp[1] = 2.
class Solution {
public int mincostTickets(int[] days, int[] costs) {
int last = days[days.length - 1];
boolean[] travel = new boolean[last + 1];
for (int d : days) travel[d] = true;
int[] dp = new int[last + 1];
for (int d = 1; d <= last; d++) {
if (!travel[d]) { dp[d] = dp[d - 1]; continue; }
dp[d] = Math.min(dp[d - 1] + costs[0],
Math.min(dp[Math.max(0, d - 7)] + costs[1], dp[Math.max(0, d - 30)] + costs[2]));
}
return dp[last];
}
}Verdict: Tiny state space.