I am trying to write a program that finds the max sum of nonadjacent elements in a 1 dimensional array and so far I have this:
def find_max_sum(arr):
incl = 0
excl = 0
for i in arr:
# Current max excluding i
new_excl = excl if excl>incl else incl
# Current max including i
incl = excl + i
excl = new_excl
# return max of incl and excl
return (excl if excl>incl else incl)
It works. My only question is how would one go about transforming this function into a recursive function without using the for loops? My brain can't seem to find a way to do this.
find_max_sum(arr)callfind_max_sum(arr[1:])orfind_max_sum(arr[:-2])(so, shrink the size of the array by some amount in each step, likely one), with a base case of an array of size 1.