sagelearnai

Minimum Cost For Tickets

Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #983

You'll travel on the given days (between 1 and 365, increasing). Passes cost costs = [1-day, 7-day, 30-day], and a pass covers that many consecutive days starting on the day you buy it. Return the minimum total cost.

Examples

text
days = [1,4,6,7,8,20], costs = [2,7,15]  →  11   (1-day on 1, 7-day on 4 (covers 4–10), 1-day on 20)
days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]  →  17

Hints

  1. Let dp[d] = the minimum cost to cover all travel days up to day d.
  2. On a day you don't travel, dp[d] = dp[d−1]. On a travel day, the last pass bought might be any of the three.

Approach

text
dp[0] = 0
for d in 1..lastDay:
    if d not a travel day: dp[d] = dp[d-1]
    else: dp[d] = min(dp[d-1] + c1, dp[max(0,d-7)] + c7, dp[max(0,d-30)] + c30)

Think "the pass covering day d was bought on day d−k+1", so before that we needed dp[d−k]. That's O(365) time. A variant indexes over the travel days and uses two pointers for the 7- and 30-day windows, which helps when the calendar is huge.

Complexity

Time: O(365). Space: O(365).

Python solution
def mincostTickets(days, costs):
    travel = set(days)
    last = days[-1]
    dp = [0] * (last + 1)
    for d in range(1, last + 1):
        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[last]
JavaScript solution
function mincostTickets(days, costs) {
  const travel = new Set(days), last = days[days.length - 1], dp = new Array(last + 1).fill(0);
  for (let d = 1; d <= last; d++) {
    if (!travel.has(d)) { dp[d] = dp[d - 1]; continue; }
    dp[d] = Math.min(dp[d - 1] + costs[0], dp[Math.max(0, d - 7)] + costs[1], dp[Math.max(0, d - 30)] + costs[2]);
  }
  return dp[last];
}