SDE & MLE Prep

983. Minimum Cost For Tickets

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]