Minimum Costs Using the Train Line

Updated on 10 June, 2025
Minimum Costs Using the Train Line header image

Problem Statement

In the problem, we are dealing with a train line that has two different routes through the city, namely the regular route and the express route. These routes connect the same set of n + 1 train stops, which are labeled from 0 to n. Your journey begins at stop 0 on the regular route.

For each stop i from 1 to n:

  • regular[i] denotes the travel expense using the regular route from stop i-1 to stop i.
  • express[i] signifies the cost using the express route for the same segment.

Additionally, to switch from the regular to express route, you incur an extra cost captured by expressCost. Switching back from express to regular, however, is free.

The task is to compute and return an array of length n, indexed from 1 to n, where each entry costs[i] represents the least expense required to travel from the initial stop 0 to stop i on either route. This problem requires consideration of both direct travel costs and transfer penalties to find the minimum possible expense to reach each subsequent stop.

Examples

Example 1

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.
- Take the regular route from stop 0 to stop 1, costing 1.
- Take the express route from stop 1 to stop 2, costing 8 + 2 = 10.
- Take the express route from stop 2 to stop 3, costing 3.
- Take the regular route from stop 3 to stop 4, costing 5.
The total cost is 1 + 10 + 3 + 5 = 19.
Note that a different route could be taken to reach the other stops with minimum cost.

Example 2

Input:

regular = [11,5,13], express = [7,10,6], expressCost = 3

Output:

[10,15,24]

Explanation:

The diagram above shows how to reach stop 3 from stop 0 with minimum cost.
- Take the express route from stop 0 to stop 1, costing 3 + 7 = 10.
- Take the regular route from stop 1 to stop 2, costing 5.
- Take the express route from stop 2 to stop 3, costing 3 + 6 = 9.
The total cost is 10 + 5 + 9 = 24.
Note that the expressCost is paid again to transfer back to the express route.

Constraints

  • n == regular.length == express.length
  • 1 <= n <= 105
  • 1 <= regular[i], express[i], expressCost <= 105

Approach and Intuition

Given the initial stop at 0 on the regular route and the described costs for moving and switching between routes, our goal is to dynamically determine the minimum cost to each stop by considering all possible ways to reach that stop:

  1. From either stop i-1 on the regular route, the minimum cost to stop i could be the sum of:

    • The previous minimum cost to stop i-1 via the regular route plus the cost from regular[i].
    • The previous minimum cost to stop i-1 via the express route plus the switching cost (expressCost if applicable) and the regular route cost (regular[i]).
  2. From stop i-1 via the express route, the minimum cost to stop i could be calculated as:

    • The previous minimum cost to stop i-1 via the express route plus the express route cost (express[i]).
    • The previous minimum cost to stop i-1 via the regular route plus the express route cost (express[i]) without any need for a switching cost because transitioning from express to regular and back to express again can be split across steps and could potentially involve no additional cost at a single step.

For each stop, we update our costs by choosing the least expensive of the available options from the calculations done in the above steps. This approach effectively uses dynamic programming to ensure that each step considers all prior optimal decisions, thereby making the problem solvable efficiently even for large inputs. The implementation of this solution would involve maintaining arrays or variables that track the minimal costs to each stop via both regular and express routes, updating them iteratively for each stop.

Solutions

  • C++
  • Java
cpp
class Solution {
public:
    vector<long long> computeMinCosts(vector<int>& standard, vector<int>& premium, int upgradeFee) {
        int size = standard.size() + 1;
        
        long minStandard = 0;
        long minPremium = upgradeFee;
        
        vector<long long> result;
        for (int i = 1; i < size; i++) {
            long costStandard = standard[i - 1] + min(minStandard, minPremium);
            long costPremium = premium[i - 1] + min(minPremium, minStandard + upgradeFee);
            
            result.push_back(min(costStandard, costPremium));
            
            minStandard = costStandard;
            minPremium = costPremium;
        }
        
        return result; 
    }
};

In this solution, the objective is to determine the minimum costs of traveling using a train system that offers both standard and premium services, along with an option to upgrade from standard to premium. The code uses the C++ programming language.

The function computeMinCosts() in the Solution class takes three parameters:

  • standard - a vector of integers representing the cost of traveling via standard class for each trip.
  • premium - a vector of integers representing the cost of traveling via premium class for each trip.
  • upgradeFee - an integer representing the cost to upgrade from standard to premium.

The function initializes two variables to track the minimum accumulated cost for each train line:

  • minStandard - initially set to 0 to indicate no cost has been accumulated for standard travel yet.
  • minPremium - starts off as the upgradeFee, representing the minimal initial cost of starting with premium class by upgrading from standard.

A result vector, result, is used to store the minimum cost for each segment of the journey.

The method iterates over each segment from 1 to the size of the standard and premium vectors. For each segment, the code computes:

  • costStandard - the cost if travelling on standard class for this segment, taking the lower cost of either continuing in standard class or switching from premium to standard.
  • costPremium - the cost if using premium class, accounting for both, continued travel in premium or a fresh upgrade from standard in this segment.

The minimum of costStandard and costPremium for the current segment is pushed into the result vector. It then updates minStandard and minPremium to the calculated costs for the current segment, ensuring that each segment's calculations are based on the optimal choices of all preceding segments.

Finally, the function returns the result vector containing the minimized costs for each segment of the journey. This implementation ensures that the traveler always spends the least amount possible, given the costs of each travel class and the upgrade fee.

java
class Solution {
    public long[] calculateMinimumCost(int[] standard, int[] express, int upgradeCost) {

        long previousStandard = 0;
        long previousExpress = upgradeCost;

        long[] result = new long[standard.length];
        for (int idx = 1; idx < standard.length + 1; idx++) {
            long costStandard = standard[idx - 1] + Math.min(previousStandard, previousExpress);
            long costExpress = express[idx - 1] + Math.min(upgradeCost + previousStandard, previousExpress);

            result[idx - 1] = Math.min(costStandard, costExpress);

            previousStandard = costStandard;
            previousExpress = costExpress;
        }

        return result;

    }
}

The provided Java solution determines the minimum cost of traveling through a train line using two potential routes: the standard line and the express line, with the option to upgrade from standard to express at a fixed cost. The method calculateMinimumCost accepts three parameters: arrays representing the cost of each station in the standard and express lines, and an integer representing the upgrade cost.

Follow these steps to understand the algorithm implemented in the Java class:

  1. Initialize two long variables, previousStandard and previousExpress, where previousStandard starts at 0, and previousExpress starts with the initial cost of upgrading.

  2. Create an array result to store the minimum cost to reach each station.

  3. Use a loop to iterate through each train station, beginning from the first station. In each iteration:

    • Calculate the cost of reaching the current station via the standard line by adding the cost at the current station to the minimum of the cost of being at the previous station on the standard or express line.
    • Similarly, calculate the cost of reaching the current station via the express line. This cost is the sum of the express line cost at the current station and the lesser of being at the previous station on the standard line plus the upgrade cost, or the express line cost at the previous station.
    • Store the minimum of these two calculated costs in the result array.
  4. Update previousStandard and previousExpress with the calculated costs for the current station to use in the next iteration.

  5. Return the result array, which now contains the minimum cost to reach each station using either the standard or express line, selecting the optimal route at each step.

This approach ensures optimal utilization of both lines based on the costs and provides a dynamic solution to minimize overall travel expenses through recursive comparison and direct computation.

Comments

No comments yet.