213. House Robber II
by Botao Xiao
213. House Robber II
Question
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
because they are adjacent houses.
Example 2:
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.
Thinking:
- Method:DP
class Solution {
public int rob(int[] nums) {
int len = nums.length;
if(len == 0) return 0;
if(len == 1) return nums[0];
if(len == 2) return Math.max(nums[0], nums[1]);
int[] dp = new int[len + 1];
dp[0] = 0;
dp[1] = 0;
for(int i = 2; i <= len; i++){
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]);
}
int[] dpp = new int[len + 1];
dpp[0] = 0;
dpp[1] = nums[0];
dpp[2] = dpp[1];
for(int i = 3; i < len; i++){
dpp[i] = Math.max(dpp[i - 1], dpp[i - 2] + nums[i - 1]);
}
dpp[len] = dpp[len - 1];
return Math.max(dp[len], dpp[len]);
}
}
二刷
- 这道题肯定是用DP解决,但是要分成两种情况:
- 如果抢了第一家,我们就不能抢最后一家。
- 如果我们抢了最后一家,就不能抢第一家。
- 这两种情况需要我们遍历两次循环,通过for循环控制。
class Solution { public int rob(int[] nums) { if(nums == null || nums.length < 1) return 0; int len = nums.length; if(1 == len) return nums[0]; int result = 0; int[] dp = new int[len + 1]; for(int i = 1; i < len; i++){ dp[i] = Math.max(dp[i - 1], nums[i - 1] + (i >= 2 ? dp[i - 2] : 0)); } int[] dp1 = new int[len + 1]; for(int i = 2; i <= len; i++){ dp1[i] = Math.max(dp1[i - 1], nums[i - 1] + dp1[i - 2]); } return Math.max(dp[len - 1], dp1[len]); } }
Subscribe via RSS