Created
October 14, 2020 18:13
-
-
Save Abdujabbar/d887dad4ef6df2acd30bdd190037b335 to your computer and use it in GitHub Desktop.
optimized version
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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