Created
May 22, 2023 23:02
-
-
Save optimistiks/9ff722c155ef56ca45b9d873c7953cf6 to your computer and use it in GitHub Desktop.
You need to find the minimum number of refueling stops that a car needs to make to cover a distance (target). Stations is an array of tuples [distance, fuel]. 1 distance = 1 fuel.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function minRefuelStops(target, startFuel, stations) { | |
| if (startFuel >= target) { | |
| // if we have enough fuel to cover the target | |
| return 0; | |
| } | |
| // we're going to store fuels of reachable stations in a max heap | |
| const heap = new MaxHeap(); | |
| // max distance that we can cover in the current moment (equals to amount of fuel since 1 mile = 1 fuel) | |
| let maxDistance = startFuel; | |
| // number of refueling stops | |
| let stops = 0; | |
| for (let i = 0; i < stations.length; ++i) { | |
| const [dist, fuel] = stations[i]; | |
| if (dist <= maxDistance) { | |
| // if we can reach this station, add it to the heap | |
| heap.push(fuel); | |
| // handle when the last stop is reachable | |
| while ( | |
| i === stations.length - 1 && | |
| heap.isEmpty() > 0 && | |
| maxDistance < target | |
| ) { | |
| // last stop may be reachable but we still need to understand what is the min number of refueling stops we need | |
| // so pop fuels out of the heap until we reach the target distance, | |
| // or until the heap is empty | |
| maxDistance += heap.pop(); | |
| stops += 1; | |
| } | |
| } else { | |
| // stop is not reachable, pop the most fuel out of the currently reachable stops and increase the max distance | |
| // decrement i so we can try to reach this stop again | |
| maxDistance += heap.pop(); | |
| stops += 1; | |
| i -= 1; | |
| } | |
| } | |
| return stops; | |
| } | |
| // O(n * logn) since heap push is logn, and we do it n times once for each station. Mem O(n) because heap. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment