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

被折叠的 条评论
为什么被折叠?



