Skip to content

Instantly share code, notes, and snippets.

@Abdujabbar
Created October 14, 2020 18:13
Show Gist options
  • Save Abdujabbar/d887dad4ef6df2acd30bdd190037b335 to your computer and use it in GitHub Desktop.
Save Abdujabbar/d887dad4ef6df2acd30bdd190037b335 to your computer and use it in GitHub Desktop.
optimized version
from typing import List
from collections import defaultdict
class Solution:
def rob(self, nums: List[int]) -> int:
N = len(nums)
is_exists_cache = defaultdict(bool)
cache_for_robbing = defaultdict(int)
def rob_houses(index, sz):
if index >= sz:
return 0
cache_key = str(sz) + str(index)
if is_exists_cache[cache_key]:
return cache_for_robbing[cache_key]
amountFromFirst = rob_houses(index + 1, sz)
amountFromSecond = rob_houses(index + 2, sz) + nums[index]
is_exists_cache[cache_key] = True
cache_for_robbing[cache_key] = max(amountFromFirst, amountFromSecond)
return cache_for_robbing[cache_key]
robingFromSecond = rob_houses(1, N)
robbingFromFirst = rob_houses(2, N - 1) + nums[0]
return max(robingFromSecond, robbingFromFirst)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment