Skip to content

Commit 19d702c

Browse files
committed
Memoization solution for the house robber problem
1 parent e2a1388 commit 19d702c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

house_robber.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# You are a professional robber planning to rob houses along a street.
2+
# Each house has a certain amount of money stashed,
3+
# the only constraint stopping you from robbing each of them is that adjacent houses have security system connected
4+
# and it will automatically contact the police if two adjacent houses were broken into on the same night.
5+
6+
# Given a list of non-negative integers representing the amount of money of each house,
7+
# determine the maximum amount of money you can rob tonight without alerting the police.
8+
9+
from typing import List
10+
from unittest import TestCase
11+
12+
13+
def rob(nums: List[int]) -> int:
14+
memo = [None] * (len(nums) + 1)
15+
return _rob(0, nums, memo)
16+
17+
18+
def _rob(i, nums, memo):
19+
if i > len(nums) - 1:
20+
return 0
21+
else:
22+
if memo[i] is not None:
23+
return memo[i]
24+
result = max(nums[i] + _rob(i + 2, nums, memo), _rob(i + 1, nums, memo))
25+
memo[i] = result
26+
return result
27+
28+
29+
class TestRob(TestCase):
30+
def test_with_empty_list(self):
31+
self.assertEqual(0, rob([]))
32+
33+
def test_with_list_zeros(self):
34+
self.assertEqual(0, rob([0, 0, 0, 0]))
35+
36+
def test_with_one_element(self):
37+
self.assertEqual(2, rob([2]))
38+
39+
def test_with_two_elements_and_last_bigger(self):
40+
self.assertEqual(2, rob([1, 2]))
41+
42+
def test_with_two_elements_and_first_bigger(self):
43+
self.assertEqual(2, rob([2, 1]))
44+
45+
def test_if_not_return_max_profit_with_adjacent_houses(self):
46+
self.assertEqual(4, rob([1, 2, 3, 1]))

0 commit comments

Comments
 (0)