LeetCode 983. Minimum Cost For Tickets

Post by ailswan Apr. 27, 2024

983. Minimum Cost For Tickets

Problem Statement

link: LeetCode.cn LeetCode You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365.

Train tickets are sold in three different ways:

a 1-day pass is sold for costs[0] dollars, a 7-day pass is sold for costs[1] dollars, and a 30-day pass is sold for costs[2] dollars. The passes allow that many days of consecutive travel.

For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8. Return the minimum number of dollars you need to travel every day in the given list of days. Example:

Input: days = [1,4,6,7,8,20], costs = [2,7,15] Output: 11

Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15] Output: 17

Solution Approach

The solution utilizes dynamic programming to calculate the minimum cost for traveling each day. It iterates through the days, considering the cost of buying a 1-day pass, a 7-day pass, or a 30-day pass, and chooses the minimum among them.

Algorithm

dp[0] = 0 dp[i] = min dp[i - 1] + costs[0] if i - 1 > 0 dp[i - 7] + costs[1] if i - 7 > 0 dp[i - 30] + costs[2] if i - 30 > 0

Implement

    class TreeNode:
  def mincostTickets(self, days: List[int], costs: List[int]) -> int:
    first, last = days[0], days[-1]
    days = set(days)
    dp = [0] * (last + 1)
    for i in range(first, last + 1):
        if i in days:
            p1 = dp[i - 1] if i - 1 > 0 else 0
            p7 = dp[i - 7] if i - 7 > 0 else 0
            p30 = dp[i - 30] if i - 30 > 0 else 0 
            dp[i] = min(p1 + costs[0], p7 + costs[1], p30 + costs[2])
        else:
            dp[i] = dp[i - 1]
    return dp[-1]