Skip to content

Commit 780c287

Browse files
committed
Add solution #871
1 parent 1288c32 commit 780c287

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,7 @@
678678
868|[Binary Gap](./0868-binary-gap.js)|Easy|
679679
869|[Reordered Power of 2](./0869-reordered-power-of-2.js)|Medium|
680680
870|[Advantage Shuffle](./0870-advantage-shuffle.js)|Medium|
681+
871|[Minimum Number of Refueling Stops](./0871-minimum-number-of-refueling-stops.js)|Hard|
681682
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|
682683
873|[Length of Longest Fibonacci Subsequence](./0873-length-of-longest-fibonacci-subsequence.js)|Medium|
683684
875|[Koko Eating Bananas](./0875-koko-eating-bananas.js)|Medium|
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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

Comments
 (0)