夯实算法-最低票价

186 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天,点击查看活动详情

题目:LeetCode

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

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

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

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

示例 1:

输入: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:

输入: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 <= days.length <= 365
  • 1 <= days[i] <= 365
  • days 按顺序严格递增
  • costs.length == 3
  • 1 <= costs[i] <= 1000

解题思路

function(int index, int costIndex) index索引那天,决定以costIndex方式去旅行花费比较小。
主函数,costIndex为0,第0天的累计花费为0。
costIndex参数来自累加消费。但是消费数值不利于dp,因此用索引代替。消费中并没有0消费的情况,因此增加第0种消费。其余三种在此基础上做-1处理。

代码实现

public int mincostTickets(int[] days, int[] costs) {
        Integer[][] dp = new Integer[days.length + 1][4];
        return this.function(days, costs, 0, 0, dp);
}

private int function(int[] days, int[] costs, int index, int costIndex, Integer[][] dp) {
    if (days.length == index) {
            return costs[costIndex - 1];
    }
    if (dp[index][costIndex] != null) {
            return dp[index][costIndex];
    }
    int ans = this.function(days, costs, index + 1, 1, dp);
    int start = days[index];
    int end7 = start + 6;
    int end30 = start + 29;
    int index7 = index;
    int index30 = index;
    for (int i = index; i < days.length; i++) {
            if (days[i] <= end7) {
                    index7 = i;
                    index30 = i;
            } else if (days[i] <= end30) {
                    index30 = i;
            } else {
                    break;
            }
    }
    ans = Math.min(ans, this.function(days, costs, index7 + 1, 2, dp));
    ans = Math.min(ans, this.function(days, costs, index30 + 1, 3, dp));
    ans = costIndex == 0 ? ans : ans + costs[costIndex - 1];
    dp[index][costIndex] = ans;
    return ans;
}

复杂度分析

  • 时间复杂度:O(N2)O(N^2)
  • 空间复杂度:O(N)O(N)

掘金(JUEJIN)  一起分享知识, Keep Learning!