ou have 2 integers as input: n and c. You are also given an array D of length n. Assume that you are currently at a gas station G0 and filled up the gas tank of your classic car Plymouth Fury. You can fill up at most c liters of gasoline in your gas fuel tank. To travel 1 km your car needs to use 1 gallon of gasoline. To reach your destination, which is the nth gas station, you need to pass the gas stations G1, ..., Gn along a highway. For a gas station Gi, where 1<= i <= n, its distance from the previous gas station Gi-1 is Di, where Di <= c. To save time, you want to choose the gas stations carefully to minimize the number of times to refuel your car, and you also do not want to run out of gas in the middle of nowhere. Write an efficient algorithm (to the best of your knowledge) to find the shortest list of gas stations where you must stop to take gas so that you can reach your destination. Formally prove that your algorithm is correct, provide pseudocode, and analyze the time complexity. Example: Input: n = 6, c = 40, D = [1
You have 2 integers as input: n and c. You are also given an array D of length n.
Assume that you are currently at a gas station G0 and filled up the gas tank of your classic car Plymouth Fury. You can fill up at most c liters of gasoline in your gas fuel tank. To travel 1 km your car needs to use 1 gallon of gasoline. To reach your destination, which is the nth gas station, you need to pass the gas stations G1, ..., Gn along a highway. For a gas station Gi, where 1<= i <= n, its distance from the previous gas station Gi-1 is Di, where Di <= c. To save time, you want to choose the gas stations carefully to minimize the number of times to refuel your car, and you also do not want to run out of gas in the middle of nowhere.
Write an efficient
Example: Input: n = 6, c = 40, D = [10, 20, 15, 5, 5, 20]
Output: G1, G4. This means you travel 10km to reach G1 and then fill up so that you can next travel (20+15+5)km to reach G4. Then you fill up at G4 so that you can travel (5+20)km to reach the destination G6.
There can be many other options with two gas stations, e.g., {G2, G3} is another option. You just need to output one if there are many options that are equally well. In this example, you cannot do better than two gas stations.
Trending now
This is a popular solution!
Step by step
Solved in 2 steps