House Robber LeetCode solution in Python

1
class Solution:
2
def rob(self, nums: List[int]) -> int:
3
# [rob1,rob2,n,n+1]
4
# 1 | 2 | 3 | 1
5
# index 0 1 2 3
6
# so upto last index it depends on previous 2 values :
7
# here upto 2nd index max rob is 1+3=4; not choosing adjacent element 2
8
# and upto 1st index max rob is 2 ; not choosing any adjacent elements
9
# so at 3rd index it depend on prev rob value and 1st index rob value+last value
10
# i.e max(2+(val at last index),4)
11
rob1 = 0
12
rob2 = 0
13
for i in nums:
14
temp = max(rob1 + i, rob2)
15
rob1 = rob2
16
rob2 = temp
17
return rob2

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0