forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
house-robber.py
41 lines (35 loc) · 1.27 KB
/
house-robber.py
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
# Time: O(n)
# Space: O(1)
#
# You are a professional robber planning to rob houses along a street.
# Each house has a certain amount of money stashed, the only constraint stopping you
# from robbing each of them is that adjacent houses have security system connected
# and it will automatically contact the police if two adjacent houses were broken into on the same night.
#
# Given a list of non-negative integers representing the amount of money of each house,
# determine the maximum amount of money you can rob tonight without alerting the police.
#
class Solution:
# @param num, a list of integer
# @return an integer
def rob(self, num):
if len(num) == 0:
return 0
if len(num) == 1:
return num[0]
num_i, num_i_1 = max(num[1], num[0]), num[0]
for i in xrange(2, len(num)):
num_i_1, num_i_2 = num_i, num_i_1
num_i = max(num[i] + num_i_2, num_i_1);
return num_i
def rob2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
last, now = 0, 0
for i in nums:
last, now = now, max(last + i, now)
return now
if __name__ == '__main__':
print Solution().rob([8,4,8,5,9,6,5,4,4,10])