Skip to main content
Back to problems
#1928
Hard Algorithms

Minimum cost to reach destination in time

Array Dynamic Programming Graph Theory
41.2% acceptance
Mar 1, 2026
962
23
There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j. In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities). Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn min_cost(max_time: i32, edges: Vec<Vec<i32>>, passing_fees: Vec<i32>) -> i32 {
    let n = passing_fees.len();
    let max_time = max_time as usize;
    let mut adj = vec![vec![]; n];
    for e in &edges {
      adj[e[0] as usize].push((e[1] as usize, e[2] as usize));
      adj[e[1] as usize].push((e[0] as usize, e[2] as usize));
    }

    // dp[t][v] = min cost to reach node v in exactly t minutes
    let inf = i32::MAX / 2;
    let mut dp = vec![vec![inf; n]; max_time + 1];
    dp[0][0] = passing_fees[0];

    for t in 0..max_time {
      for v in 0..n {
        if dp[t][v] == inf {
          continue;
        }
        for &(u, w) in &adj[v] {
          let new_t = t + w;
          if new_t <= max_time {
            dp[new_t][u] = dp[new_t][u].min(dp[t][v] + passing_fees[u]);
          }
        }
      }
    }

    let ans = (0..=max_time).map(|t| dp[t][n - 1]).min().unwrap();
    if ans == inf { -1 } else { ans }
  }
}