Leetcode 983. Minimum Cost For Tickets解题报告(python)

本文介绍了一种使用动态规划解决火车票购买策略的问题,旨在找出在特定旅行日期内,以最低成本购买1天、7天或30天火车票的最佳方式。通过分析旅行日期数组和不同票种的价格,提供了一个Python实现的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1111. 983. Minimum Cost For Tickets

  1. Minimum Cost For Tickets python solution

题目描述

In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365.
Train tickets are sold in 3 different ways:
a 1-day pass is sold for costs[0] dollars;
a 7-day pass is sold for costs[1] dollars;
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: day 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.

在这里插入图片描述

解析

首先理解题目的意思,题目中days数组里的数字,代表着可以出去旅游的日子。并不代表着从哪天开始到哪天结束。
动态规划,详见代码!

// An highlighted block
class Solution:
    def mincostTickets(self, days: List[int], costs: List[int]) -> int:
        days_dict = collections.Counter(days)
        table = [0 for i in range(0, days[-1]+1)]
        
        for i in range(0, days[-1]+1):
            if i not in days_dict:
                table[i] = table[i-1]
            else:
       # Used max to identify if the index exists 
                table[i] = min(
                    table[max(0,i-1)]+costs[0], # per days value
                    table[max(0,i-7)]+costs[1], # per week value
                    table[max(0,i-30)]+costs[2] # per year value
                )
        return table[-1]
         

Reference

https://leetcode.com/problems/minimum-cost-for-tickets/discuss/228421/Python-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值