You've successfully subscribed to The Daily Awesome
Welcome back! You've successfully signed in.
Success! Your billing info is updated.
Billing info update failed.

# 983. 最低票价 - Minimum Cost For Tickets

【动态规划】

• 一张为期一天的通行证售价为 costs[0] 美元；
• 一张为期七天的通行证售价为 costs[1] 美元；
• 一张为期三十天的通行证售价为 costs[2] 美元。

### Example:

输入：days = [1,4,6,7,8,20], costs = [2,7,15]



输入：days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]



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

## Solutions

### Solution 【动态规划】 ( 6ms)

class Solution {
public int mincostTickets(int[] days, int[] costs) {
int[] minCosts = new int[days[days.length - 1] + 1];
Set<Integer> daySet = new HashSet<>();
for (int day : days) {
}
int ticket1 = costs[0];
int ticket7 = costs[1];
int ticket30 = costs[2];
for (int i = 1, length =  minCosts.length; i < length; i++) {
if (!daySet.contains(i)) {
minCosts[i] = minCosts[i - 1];
continue;
}
minCosts[i] = getMinOfThree(
minCosts[i - 1] + ticket1,
minCosts[Math.max(0, i - 7)] + ticket7,
minCosts[Math.max(0, i - 30)] + ticket30);
}
return minCosts[minCosts.length - 1];
}

private int getMinOfThree(int a, int b, int c) {
int result = a < b ? a : b;
if (c < result) {
result = c;
}
return result;
}
}


### Solution 【动态规划】 ( 4ms)

class Solution {
public int[] dp = new int[366];
public int[] costs;
public int r(int[] days, int i, int cur){
if(cur <= days[0]){
return 0;
}
if(dp[cur] != 0){
return dp[cur];
}
while (days[i] >= cur){
i--;
}
int a = r(days, i, days[i]) + costs[0];
int b = r(days, i, days[i] - 6) + costs[1];
int c = r(days, i, days[i] - 29) + costs[2];
int min = Math.min(a,Math.min(b,c));
dp[cur] = min;
return min;
}
public int mincostTickets(int[] days, int[] costs) {
this.costs = costs;
return r(days,days.length - 1, days[days.length - 1] + 1);
}
}



Reference