Bobby J.

asked • 04/08/22

How would I solve this dynamic programming question with a table?

Once again your are going on a long bike ride with your e-bike. You must ride exactly n miles. You will need to replace your battery along the way. The bike trail is lined with battery pick-up stations, where you can trade your battery for a newly charged battery. There is one battery station at every mile marker. However, unlike in our class problem, there are a selection of m differently-sized battery options at each station. With all these options, you decide not to waste any battery charges. That means that for any battery you select, you must ride until it is empty before stopping to replace your battery. For example, at mile 0 if you pick a battery of size 3, you must ride 3 miles before changing your battery. The goal is to determine if it possible to arrive at mile marker n using this new energy-efficient approach.

  1. 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 your algorithm should be True if there is a route to mile n, and False otherwise. Provide a dynamic programming solution to this problem, and determine the runtime of your algorithm. You do not need to provide the list of stopping stations.

1 Expert Answer

By:

Donald W. answered • 04/08/22

Tutor
5.0 (214)

Senior Software Engineer with over 25 years of industry experience

Donald W.

My solution assumes that it's ok to waste some charge of the last battery because you can have enough charge to bike past the endpoint. If that assumption is invalid, then we just need to change the base case of the recursion a little bit.
Report

04/08/22

Donald W.

Alternatively, you could do this iteratively using a stack or a queue, but I think the recursive solution is more intuitive.
Report

04/08/22

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.