983. Minimum Cost For Tickets
Asked at 13Meta33Amazon28Bloomberg18Google17Microsoft16Infosys45Grab100Roku100Turing84Adobe55EPAM Systems51TikTok41Uber22
Problem
days lists the days of the year (1–365) you will travel, ascending. A 1-day pass costs costs[0], a 7-day pass costs[1] and a 30-day pass costs[2]; passes cover consecutive days. Return the minimum cost to cover every travel day.
Example: days = [1,4,6,7,8,20], costs = [2,7,15] → 11
dp[d] = min cost to cover travel up to day d. Non-travel day: dp[d−1]; travel day: min(dp[d−1] + c1, dp[d−7] + c7, dp[d−30] + c30) (negative index → 0).
Complexity: O(365).
class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
travel = set(days)
dp = [0] * (days[-1] + 1)
for d in range(1, len(dp)):
if d not in travel:
dp[d] = dp[d - 1]
else:
dp[d] = min(dp[d - 1] + costs[0], dp[max(0, d - 7)] + costs[1], dp[max(0, d - 30)] + costs[2])
return dp[-1]
assert Solution().mincostTickets([1, 4, 6, 7, 8, 20], [2, 7, 15]) == 11
assert Solution().mincostTickets([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 7, 15]) == 17
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];
}
}
func mincostTickets(days []int, costs []int) int {
last := days[len(days)-1]
travel := make([]bool, last+1)
for _, d := range days {
travel[d] = true
}
dp := make([]int, last+1) // dp[d] = cheapest cover of all travel days up to d
for d := 1; d <= last; d++ {
if !travel[d] {
dp[d] = dp[d-1]
continue
}
dp[d] = min(dp[d-1]+costs[0], dp[max(0, d-7)]+costs[1], dp[max(0, d-30)]+costs[2])
}
return dp[last]
}