Minimum Costs Using the Train Line — LeetCode 2361 Python Solution
- Problem
- #2361
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
A train line going through a city has two routes, the regular route and the express route. Both routes go through the same n + 1 stops labeled from 0 to n.
Example
- Input
- regular = [1,6,9,5], express = [5,2,3,10], expressCost = 8
- Output
- [1,7,14,19]
- Explanation
- The diagram above shows how to reach stop 4 from stop 0 with minimum cost.
Python solution
class Solution:
def minimumCosts(
self, regular: List[int], express: List[int], expressCost: int
) -> List[int]:
n = len(regular)
f = [0] * (n + 1)
g = [inf] * (n + 1)
cost = [0] * n
for i, (a, b) in enumerate(zip(regular, express), 1):
f[i] = min(f[i - 1] + a, g[i - 1] + a)
g[i] = min(f[i - 1] + expressCost + b, g[i - 1] + b)
cost[i - 1] = min(f[i], g[i])
return costComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the number of stations auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2361. Minimum Costs Using the Train Line is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2361. Minimum Costs Using the Train Line?
- LeetCode 2361. Minimum Costs Using the Train Line is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2361. Minimum Costs Using the Train Line?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2361. Minimum Costs Using the Train Line?
- The Python solution on this page uses O(n), where n is the number of stations auxiliary space.
- What topics does LeetCode 2361. Minimum Costs Using the Train Line cover?
- LeetCode 2361. Minimum Costs Using the Train Line is tagged Array and Dynamic Programming on LeetCode.
- Is LeetCode 2361. Minimum Costs Using the Train Line a premium problem?
- Yes. LeetCode 2361. Minimum Costs Using the Train Line is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.