(Note: Robbing is against the law! đ The below is just the actual Leetcode question phrasing reproduced verbatim.)
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 400
Leetcode Solution (Python)
class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
# dp[i] max amount for nums[0:i]
dp = [-1 for i in range(n+1)]
# Recursive function that returns dp[i]
def recursive(i):
if i<=0:
return 0
if dp[i]!=-1:
return dp[i]
else:
dp[i] = max(recursive(i-1), nums[i-1]+recursive(i-2))
#print(dp)
return dp[i]
return recursive(n)
Cracking the Coding Interview: 189 Programming Questions and Solutions

