
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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
1 <= nums.length <= 1000 <= nums[i] <= 400인접한 집을 접근할 수 없기 때문에, 두 가지 선택지가 존재함.
1. i번째 집과, i-2번째집을 도둑질하는 방법. prev2 + num
2. i번째 집을 도둑질하지 않고 i-1번째 집을 도둑질하는 방법. prev1
두가지 방법 중 더 큰 값을 골라서 i+1번째 집을 선택할지 말지 판단하기 위해 i번째 집을 도둑질하는 선택지는 prev1에, i-1번째 집을 도둑질하는 선택지는 prev2에 다시 저장함.
class Solution {
public int rob(int[] nums) {
int prev1 = 0;
int prev2 = 0;
for (int num: nums) {
int tmp = prev1;
prev1 = Math.max(prev2 + num, prev1);
prev2 = tmp;
}
return prev1;
}
}