Skip to content

2361. Minimum Costs Using the Train Line 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  vector<long long> minimumCosts(vector<int>& regular, vector<int>& express,
                                 int expressCost) {
    const int n = regular.size();
    vector<long long> ans(n);
    // the minimum cost to reach the current stop in a regular route
    long dpReg = 0;
    // the minimum cost to reach the current stop in an express route
    long dpExp = expressCost;

    for (int i = 0; i < n; ++i) {
      const long prevReg = dpReg;
      const long prevExp = dpExp;
      dpReg = min(prevReg + regular[i], prevExp + 0 + regular[i]);
      dpExp = min(prevReg + expressCost + express[i], prevExp + express[i]);
      ans[i] = min(dpReg, dpExp);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public long[] minimumCosts(int[] regular, int[] express, int expressCost) {
    final int n = regular.length;
    long[] ans = new long[n];
    // the minimum cost to reach the current stop in a regular route
    long dpReg = 0;
    // the minimum cost to reach the current stop in an express route
    long dpExp = expressCost;

    for (int i = 0; i < n; ++i) {
      final long prevReg = dpReg;
      final long prevExp = dpExp;
      dpReg = Math.min(prevReg + regular[i], prevExp + 0 + regular[i]);
      dpExp = Math.min(prevReg + expressCost + express[i], prevExp + express[i]);
      ans[i] = Math.min(dpReg, dpExp);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
  def minimumCosts(
      self,
      regular: list[int],
      express: list[int],
      expressCost: int,
  ) -> list[int]:
    n = len(regular)
    ans = [0] * n
    # the minimum cost to reach the current stop in a regular route
    dpReg = 0
    # the minimum cost to reach the current stop in an express route
    dpExp = expressCost

    for i in range(n):
      prevReg = dpReg
      prevExp = dpExp
      dpReg = min(prevReg + regular[i], prevExp + 0 + regular[i])
      dpExp = min(prevReg + expressCost + express[i], prevExp + express[i])
      ans[i] = min(dpReg, dpExp)

    return ans