213. House Robber II
Posted 鱼与海洋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了213. House Robber II相关的知识,希望对你有一定的参考价值。
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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
public 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[] dp1 = new int[n]; int[] dp2 = new int[n]; dp1[0] = nums[0]; dp1[1] = Math.max(nums[1], nums[0]); for(int i = 2 ; i < n-1 ; i++){ dp1[i] = Math.max(dp1[i-1] , dp1[i-2] + nums[i]); } dp2[n-1] = nums[n-1]; dp2[n-2] = Math.max(nums[n-1], nums[n-2]); for(int i = n-3 ; i > 0 ; i--){ dp2[i] = Math.max(dp2[i+1] , dp2[i+2] + nums[i]); } return Math.max(dp2[1] , dp1[n-2]); } }
以上是关于213. House Robber II的主要内容,如果未能解决你的问题,请参考以下文章