This is the Robber problem where a thief cannot steal from two adjacent homes but wants to maximize loot.
Example: input: arr = [2, 10, 3, 6, 8, 1, 7] output: 25 explanation: The greatest amount of money that a robber can get is 25, by the stealing the house 1, 4, and 6 (arr[1]+arr[4]+arr[6] = 10+8+7 = 25)
This solution does work.
def rob(arr):
arr = tuple(arr)
memory = {}
def helper(i=0):
if i >= len(arr):
return 0
if i not in memory:
steal = arr[i] + helper(i+2)
skip = helper(i+1)
memory[i] = max(steal, skip)
return memory[i]
return helper()
But this solution returns 0.
def rob(arr):
arr = tuple(arr)
memory = {}
def helper(i=0):
if i >= len(arr):
return 0
elif memory[i]:
return memory[i]
else:
steal = arr[i] + helper(i+2)
skip = helper(i+1)
memory[i] = max(steal, skip)
return memory[i]
return helper()
The key difference is the presence of the elif statement. Frankly, I don't understand how there is a difference in control flow. I believe these to be synonymous and should execute the same. However, this is not the case.
Could someone explain?