
Donald W. answered 04/02/22
Experienced and Patient Tutor for Math and Computer Science
To use dynamic programming, we should have an array that stores the number of charges it would take to get to the end if we started at mile i. We'll call this array "dp" and initialize it to all 0's.
dp[] = { 0 }
And then our function can use this array to calculate our answer:
minimumStops ( b, startMile, endMile ) {
// First check our dp array to see if we've calculated this before
if (dp[startMile] != 0) {
return dp[startMile]
}
// Otherwise, charge up and see if we can reach the end with a single charge
charge = b[startMile]
if (charge >= endMile - startMile) {
dp[startMile] = 1
return 1
}
// If we can't, try recharging at every charging station within "charge" miles and see which one is the minimal
int charges = INT_MAX
for (int i=1; i<=charge && startMile + i < endMile; i++) {
charges = min(charges, minimumStops(b, startMile + i, endMile))
}
// Our answer is one more than that minimal number of charges
dp[startMile] = charges + 1;
return charges + 1;
}
And we can then just call this function with our starting conditions to find the answer:
minimumStops( b, 0, n );
As for the runtime performance of this algorithm, I think it's O(n*m), where n is the number of miles to travel and m is the average battery capacity at each pickup station, because that's the number of comparisons we have to do for every battery replacement to find the minimum.

Donald W.
It would be quite similar. We would have to change the logic to try all the different batteries at each location rather than just trying every mile between 1 and "charge".04/08/22

Donald W.
I see that you posted that as a separate question. I just submitted an answer for it.04/08/22
Bobby J.
What if the question is if it is possible to arrive at n and we are not wasting any battery charges so for any battery you select, you must ride until it is empty before stopping to replace your battery. The input to the problem is an array B[0 . . . n, 1 . . . m], where B[i, j] stores the battery life (in miles) of battery j at station i. For example, station 0 has battery sizes B[0, 1], B[0, 2], . . . , B[0, m]. Assume you start the trail at mile 0, and that you may select to start with any of the batteries at that station. The output to the algorithm should be True if there is a route to mile n, and False otherwise.04/08/22