Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
这是室内抢劫问题的延伸版本。
在这个问题中,所有的房屋排列成一圈,也就是第一个房屋与最后一个房屋相邻。同时,触动警报系统的条件仍然是相邻房屋被盗。
Analysis:与之前的问题不同之处是,首尾房屋相邻,也就是首尾房屋不能同时被选作抢劫房屋。因此可以看做两个问题,若选中第一个房屋则最后一个房屋不能选;做选中最后一个房屋则第一个房屋不能选。因此只需做两次DP即可,最终选择结果最大的方案。
Answer:
public class Solution { public int rob(int[] nums) { if(nums.length == 0 || nums == null) return 0; if(nums.length == 1) return nums[0]; if(nums.length == 2) return Math.max(nums[0], nums[1]); return Math.max(getRob(nums, 0, nums.length-2), getRob(nums, 1, nums.length-1)); } public int getRob(int[] nums, int s, int t) {//要注意下面s t 参数的设置 int n = t - s + 1; int[] dp = new int[n]; dp[0] = nums[s]; dp[1] = Math.max(nums[s], nums[s+1]); for(int i=2; i<n; i++){ dp[i] = Math.max(dp[i-1], dp[i-2]+nums[s+i]); } return dp[n-1]; } }