-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path198_house_robber.py
More file actions
47 lines (38 loc) · 1012 Bytes
/
198_house_robber.py
File metadata and controls
47 lines (38 loc) · 1012 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
L = len(nums)
if L == 0:
return(0)
elif L == 1:
return(nums[0])
prevs = {}
current = 2
prevs[0] = nums[0]
prevs[1] = max(nums[0], nums[1])
while current < L:
newVal = nums[current] + prevs[current-2]
oldVal = prevs[current-1]
if newVal > oldVal:
prevs[current] = newVal
else:
prevs[current] = oldVal
current += 1
return(prevs[L-1])
'''
#from the web:
def rob(self, nums: 'List[int]') -> 'int':
dp = 0, 0
for num in nums:
dp = dp[1] + num, max(dp)
return max(dp)
'''
if __name__ == '__main__':
test1 = [2,7,9,3,1]
test2 = [1,2,3,1]
sol = Solution()
assert(sol.rob(test1) == 12)
assert(sol.rob(test2) == 4)