题目

在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行。在接下来的一年里,你要旅行的日子将以一个名为 days 的数组给出。每一项是一个从 1 到 365 的整数。

火车票有三种不同的销售方式:

一张为期一天的通行证售价为 costs[0] 美元;
一张为期七天的通行证售价为 costs[1] 美元;
一张为期三十天的通行证售价为 costs[2] 美元。
通行证允许数天无限制的旅行。 例如,如果我们在第 2 天获得一张为期 7 天的通行证,那么我们可以连着旅行 7 天:第 2 天、第 3 天、第 4 天、第 5 天、第 6 天、第 7 天和第 8 天。

返回你想要完成在给定的列表 days 中列出的每一天的旅行所需要的最低消费。

示例1:

1
2
3
4
5
6
7
8
输入:days = [1,4,6,7,8,20], costs = [2,7,15]
输出:11
解释:
例如,这里有一种购买通行证的方法,可以让你完成你的旅行计划:
在第 1 天,你花了 costs[0] = $2 买了一张为期 1 天的通行证,它将在第 1 天生效。
在第 3 天,你花了 costs[1] = $7 买了一张为期 7 天的通行证,它将在第 3, 4, ..., 9 天生效。
在第 20 天,你花了 costs[0] = $2 买了一张为期 1 天的通行证,它将在第 20 天生效。
你总共花了 $11,并完成了你计划的每一天旅行。

示例2:

1
2
3
4
5
6
7
输入:days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
输出:17
解释:
例如,这里有一种购买通行证的方法,可以让你完成你的旅行计划:
在第 1 天,你花了 costs[2] = $15 买了一张为期 30 天的通行证,它将在第 1, 2, ..., 30 天生效。
在第 31 天,你花了 costs[0] = $2 买了一张为期 1 天的通行证,它将在第 31 天生效。
你总共花了 $17,并完成了你计划的每一天旅行。

提示:

1
2
3
4
5
1 <= days.length <= 365
1 <= days[i] <= 365
days 按顺序严格递增
costs.length == 3
1 <= costs[i] <= 1000

思路

动态规划。

ans[i] = min(ans[i-1]+costs[0] + ans[i-7]+costs[1] + ans[i-30]+costs[2]);

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public int mincostTickets(int[] days, int[] costs) {
int len = days.length;
int[] results = new int[len];
for(int i=0; i<len; ++i){
results[i] = Integer.MAX_VALUE;
}
// 防止一周或者一月的火车票更便宜的情况出现
int minCost = Math.min(Math.min(costs[0],costs[1]),costs[2]);
results[0] = costs[0];
// 动态规划寻找最优值,分三种情况,计划时间一周内,一周到一个月,一个月以上
for(int i=1; i<len; ++i){
if(days[i]<=7){
results[i] = Math.min(minCost+results[i-1],costs[1]);
}else if(7<days[i]&&days[i]<=30){
// 遍历具今天最近的一周外的时间
int j=i;
while(days[j]>days[i]-7){
j--;
if(j<0) break;
}
// 这种情况是如果最开始的到当前时间都在一周内,例如[5,7,8,9]
int tmp0 = j<0?0:results[j];
results[i] = Math.min(Math.min(results[i-1]+minCost,costs[1]+tmp0),costs[2]);
}else if(30<days[i]){
// 同上
int k=i;
while(days[k]>days[i]-30){
k--;
if(k<0) break;
}
int m=i;
while(days[m]>days[i]-7 && m>0){
m--;
if(m<0) break;
}
int tmp1 = k<0?0:results[k];
int tmp2 = m<0?0:results[m];
results[i] = Math.min(Math.min(results[i-1]+minCost,costs[2]+tmp1),costs[1]+tmp2);
}
}
return results[len-1];
}
}

大神的做法,扩充dp数组,实现算法的一致,即简化了代码,又提高了代码的运行效率。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int mincostTickets(int[] days, int[] costs) {
boolean[] rec = new boolean[365+1];
for(int day:days)
rec[day] = true;
int lastDay = days[days.length-1]+30;
// 扩充一个月dp数组使得判定条件一致
int[] dp = new int[366+30];
for(int i=31; i<=lastDay; ++i){
if(rec[i-30])
dp[i] = Math.min(Math.min(dp[i-1]+costs[0],dp[i-7]+costs[1]),dp[i-30]+costs[2]);
else
dp[i]=dp[i-1];
}
return dp[lastDay];
}
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-cost-for-tickets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。