DAY 29
0
Software Development

## [Day 29] 從LeetCode學演算法 - 0198. House Robber (Easy)

``````Question:
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.
``````
``````Example 1:
Input: [1,2,3,1]
Output: 4
Explanation:
Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
``````
``````Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation:
Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
``````

(選擇不動第i-1間，並偷了第i間，

rob[0] = nums[0] (第一間不用考慮前面的影響)
rob[1] = max(nums[0], nums[1]) (兩間選一間偷)

Java:

``````class Solution {
public int rob(int[] nums) {
if (nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
int n = nums.length;
int[] rob = new int[n];
rob[0] = nums[0];
rob[1] = Math.max(nums[0], nums[1]);
for(int i = 2; i < n; i++) {
rob[i] = Math.max(rob[i-1], rob[i-2] + nums[i]);
}
return rob[n-1];
}
}
``````

Python:

``````class Solution:
def rob(self, nums: List[int]) -> int:
l = len(nums)
if l == 0:
return 0
if l == 1:
return nums[0]
rob = [0] * l
rob[0] = nums[0]
rob[1] = max(nums[0], nums[1])

for i in range(2, l):
rob[i] = max(nums[i] + rob[i-2], rob[i-1])

return rob[-1]
``````

「時間/空間複雜度？」
(O(N), O(N)，掃過一次nums陣列，

「空間複雜度可以降低嗎？」
(可以！可以觀察出每個rob的值之間的關聯只有和前2個值有關(i-2和i-1)

``````int tmp = robprev;
robprev = robnext;
robnext = Math.max(robprev, tmp + nums[i]);
``````