HardNo. 2361LeetCode Premium

Minimum Costs Using the Train Line — LeetCode 2361 Python Solution

Topics
Array, Dynamic Programming
Reading time
3 min

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

PythonSolution
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 cost

Complexity

Time
O(n)
Space · auxiliary
O(n)where n is the number of stations

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

Related problems
No.ProblemDifficulty
2369Check if There is a Valid Partition For The ArrayMedium
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.