Rikko-213 House Robbery II
1. Topic
213. Dajia Palace II
You are a professional thief planning to rob houses along the street, each of which has a certain amount of cash hidden in it. All the houses in this place are in a circle , which means that the first house and the last house are right next to each other. At the same time, adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are broken into by thieves at the same night, the system will automatically call the police .
Given an array of non-negative integers representing the amount stored in each house, calculate the maximum amount you can steal tonight without setting off the alarm .
Example 1:
输入:nums = [2,3,2]
输出:3
解释:你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。
2. Analysis
- topic. The only difference between this question and 198 Dajiajieshe is that the beginning and the end are connected , so when traversing, the first should not be the last, or the tail should not be the first, in these two cases.
- Seeing this topic, the first thing that comes to mind is that they cannot be adjacent, so if we want to steal the i-1 family, then we need to consider that the previous i-1 family cannot be stolen, and the i-2 family can be stolen , so we probably It can be known that this is a dynamic programming problem.
- According to the above analysis, dp[i] is the maximum amount when we steal the current i house. Then we can deduce the formula as: dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]).
initialization. - Traversing, in two cases, multiple functions perform interval calls .
3. Code and comments
class Solution {
public int rob(int[] nums) {
// 1.第一种就是要最后一个房屋
// 2.第二种就是不要最后一个房屋
if (nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
if (nums.length == 2) return Math.max(nums[0], nums[1]);
return Math.max(robRange(nums, 0, nums.length - 1), robRange(nums, 1, nums.length));
}
public int robRange(int[] nums, int start, int end){
int[] dp = new int[end];
dp[start] = nums[start];
dp[start + 1] = Math.max(nums[start + 1], dp[start]);
for (int i = start + 2; i < end; i++){
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
}
return dp[end - 1];
}
}
4. Practice
Link to link to the topic: 213. Robbery II