乘坐火车路线的最少费用
难度:
标签:
题目描述
代码结果
运行时间: 348 ms, 内存: 40.4 MB
/*
* LeetCode 2361: Minimum Costs Using the Train Line
*
* Problem statement: You are given a list of train stations and the cost to travel between each pair of adjacent stations. Find the minimum cost to travel from the first station to the last station.
*
* Approach using Java Streams:
* 1. Use dynamic programming but with a more functional approach using Java Streams.
* 2. Initialize a list of costs with the first station having a cost of 0 and others as Integer.MAX_VALUE.
* 3. Use stream operations to iterate over the stations and calculate the minimum cost.
*/
import java.util.*;
import java.util.stream.*;
public class MinimumTrainCostStream {
public int minCost(int[] costs) {
int n = costs.length;
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
IntStream.range(0, n)
.forEach(i -> dp[i + 1] = Math.min(dp[i + 1], dp[i] + costs[i]));
return dp[n];
}
}
解释
方法:
该题解采用动态规划的方式来解决乘坐火车路线的最少费用问题。它定义了两个数组reg和exp,分别用来记录到达每一站点时仅通过常规路线和通过快速路线累积的最小费用。此外,使用ans数组来存储到达每一站的总体最小费用。对于每一站点i,更新reg[i+1]为从上一站通过常规路线到达当前站的费用;exp[i+1]则是比较继续使用快速路线或者从常规路线转换到快速路线的费用,取较小值。最终,ans数组中存储的每个元素即为到达相应站点的最小费用。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么在动态规划中,要分别维护常规路线和快速路线的费用数组?这样做的具体好处是什么?
▷🦆
在更新快速路线费用`exp[i+1] = min(exp[i] + express[i], reg[i+1] + expressCost)`时,为什么要考虑从常规路线转换到快速路线的费用?
▷🦆
动态规划解决方案中的`ans`数组是如何确保每个站点达到的费用都是最小的?
▷🦆
在实现中,对于数组`reg`, `exp`, 和`ans`的初始值设置有何重要性,尤其是设置为`inf`的含义是什么?
▷