FastPrepMinimum Fuel Cost Between Cities
Problems/Minimum Fuel Cost Between Cities

Minimum Fuel Cost Between Cities

Microsoft logoMicrosoft● HardFULLTIMEOA
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source specifies weighted undirected cities, per-city fuel prices, an unlimited tank, minimum cost from one city to another, -1 when unreachable, and an example result of 27. It omits the runner representation; the judged core task matches the visible source at about 98%.

There are n cities connected by undirected roads. Each road [u, v, distance] consumes distance units of fuel. Fuel costs fuelPrices[i] per unit in city i.

You start in start with an empty, unlimited-capacity fuel tank. At any visited city, you may buy any nonnegative amount of fuel before taking another road. Return the minimum total cost required to reach destination, or -1 if it is unreachable.

Function

minFuelCost(n: int, roads: int[][], fuelPrices: int[], start: int, destination: int) → long

Examples

Example 1

n = 3roads = [[0,1,3],[1,2,6]]fuelPrices = [5,2,9]start = 0destination = 2return = 27

Buy 3 units at city 0 for 15, then 6 units at city 1 for 12. The total is 27.

Example 2

n = 4roads = [[0,1,5],[0,2,1],[2,1,1],[1,3,2],[2,3,10]]fuelPrices = [10,8,2,9]start = 0destination = 3return = 16

Travel 0 -> 2 -> 1 -> 3. The first unit costs 10; after reaching city 2, the remaining three units cost 2 each.

Constraints

  • 1 <= n <= 200
  • 0 <= roads.length <= 2 * 10^4
  • Every road has two distinct valid endpoints and a positive distance.
  • 1 <= fuelPrices[i] <= 10^6
  • 0 <= start, destination < n

More Microsoft problems

  • Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
  • Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
  • Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
All Microsoft interview questionsSee Microsoft hiring insights
Saved
class Solution {
    public long minFuelCost(int n, int[][] roads, int[] fuelPrices, int start, int destination) {
        // Your code here
    }
}
Checking account…