I'm practising some Amazon interview coding exercises and I'm stuck with this exercise.
In a nutshell, given a list l and an integer d, I have to split the list into d parts such that the sum of the max of each part is the smallest, for example, with l = [10,2,20,5,15,10,1], d = 3 should return 31 as the best option is [10,2,20,5,15],[10],[1] -> 20+10+1 = 31.
Link to the problem: Problem
I thought about splitting the list in 2 and calling recursively with the first part and d-1, and taking the max of the second part (this second part will start having one element and we will add an element to this part in each iteration).
I did this and I'm getting the "maximum recursion depth exceeded while calling a Python object" error. I know the solution to this problem can be found easily but I want to understand why is this approach not working.
def getmin(l, d):
# base case, if the list has d elements each element will be a sublist
if len(l)==d:
return sum(l)
else:
minn = float("inf")
for i in range(1, len(l)-d+1):
val = getmin(l[0:-i], d-1) + max(l[-i:])
if minn > val:
minn = val
return minn