Home Leetcode

198. House Robber

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:

Let h0,,hnh_0, \dotsc, h_n represent the money in houses 0,,n0, \dotsc, n, and let OPT(i)OPT(i) represent the maximum amount of money that can be robbed from houses i,,ni, \dotsc, n. At the next house hih_i, the robber has two choices:

Top-Down

def rob(self, nums: List[int]) -> int:
	def rob_subset(i: int) -> int:
		"""Return the optimal money that we can rob from houses 
		in nums[i:] without alerting the police.
		"""
		if i >= len(nums):
			# if there are no houses to rob, we can't make any money!
			return 0
		else:
			# either rob the first house and skip the next one, 
			# or skip the first house and rob the rest
			if i + 1 not in solutions:
				solutions[i + 1] = rob_subset(i + 1)
			if i + 2 not in solutions:
				solutions[i + 2] = rob_subset(i + 2)
			
			return max(nums[i] + solutions[i + 2], solutions[i + 1])
	
	solutions = {}
	return rob_subset(0)

Bottom-up

A naive bottom-up implementation uses default values for hn+1h_{n+1} and hn+2h_{n+2}.

def rob(self, nums: List[int]) -> int:
	memo = {
		len(nums): 0,
		len(nums) + 1: 0
	}

	for i in range(len(nums) - 1, -1, -1):
		memo[i] = max(nums[i] + memo[i + 2], memo[i + 1])

	return memo[0]

However, notice that calculating OPT(i)OPT(i) only requires the previous two values, so we don’t have to memoise every value.

def rob(self, nums: List[int]) -> int:
	i_plus_one = 0
	i_plus_two = 0

	for i in range(len(nums) - 1, -1, -1):
		opt_i = max(nums[i] + i_plus_two, i_plus_one)
		i_plus_one, i_plus_two = opt_i, i_plus_one

	return i_plus_one

Time Complexity

Let nn be the number of houses. Then there is one loop with constant time iterations and nn iterations, so the algorithm takes O(n)\mathcal{O}(n) time.

Space Complexity

Since we only need to store 2 variables, the space complexity is constant.