I was given the following assignment:
There is
n
gram of mineral to be dug up on a certain asteroid. At the beginning there is only one robot at our disposal. Each robot can do one of two activities in a day (which take up the whole day):
- dig up 1 gram of mineral
- clone itself (the clone can only take action the next day)
Write a function that returns the minimum number of days needed to dig up at least
n
grams of mineral.
Of course, I immediately realised that this was a dynamic programming problem, but I have no idea how to solve the problem this way.
The only thing I managed to do was the naive recursive solution, which doesn't pass all the tests, which doesn't surprise me, because n
can be up to a million:
def mining_rec(n, r = 1, d = 0):
if n <= 0:
return d
if r >= n:
return d + 1
if r == 1:
return min(mining_rec(n - 1, r, d + 1), mining_rec(n, r + 1, d + 1))
else:
for i in range(r + 1):
mining_robots = i
cloning_robots = r - i
return mining_rec(n - mining_robots, r + cloning_robots, d + 1)
Do you have any ideas on how this could be done using dynamic programming?
from functools import cache
at the top of the file, and then add@cache
before the function you want memoized.return
in yourfor
loop cannot be right: your loop will only make one iteration.