|
| 1 | +/** |
| 2 | + * 871. Minimum Number of Refueling Stops |
| 3 | + * https://leetcode.com/problems/minimum-number-of-refueling-stops/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * A car travels from a starting position to a destination which is target miles east of the |
| 7 | + * starting position. |
| 8 | + * |
| 9 | + * There are gas stations along the way. The gas stations are represented as an array stations |
| 10 | + * where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles |
| 11 | + * east of the starting position and has fueli liters of gas. |
| 12 | + * |
| 13 | + * The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in |
| 14 | + * it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, |
| 15 | + * it may stop and refuel, transferring all the gas from the station into the car. |
| 16 | + * |
| 17 | + * Return the minimum number of refueling stops the car must make in order to reach its destination. |
| 18 | + * If it cannot reach the destination, return -1. |
| 19 | + * |
| 20 | + * Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. |
| 21 | + * If the car reaches the destination with 0 fuel left, it is still considered to have arrived. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number} target |
| 26 | + * @param {number} startFuel |
| 27 | + * @param {number[][]} stations |
| 28 | + * @return {number} |
| 29 | + */ |
| 30 | +var minRefuelStops = function(target, startFuel, stations) { |
| 31 | + const dp = [startFuel]; |
| 32 | + const stationCount = stations.length; |
| 33 | + |
| 34 | + for (let i = 0; i < stationCount; i++) { |
| 35 | + dp.push(0); |
| 36 | + for (let stops = i; stops >= 0; stops--) { |
| 37 | + if (dp[stops] >= stations[i][0]) { |
| 38 | + dp[stops + 1] = Math.max(dp[stops + 1], dp[stops] + stations[i][1]); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + for (let stops = 0; stops <= stationCount; stops++) { |
| 44 | + if (dp[stops] >= target) return stops; |
| 45 | + } |
| 46 | + |
| 47 | + return -1; |
| 48 | +}; |
0 commit comments