Leetcode 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.


解题思路:

Dynamic Programming

This is an extension of House Robber. There are two cases here

1) 1st element is included and last is not included

2) 1st is not included and last is included.

Therefore, we can use the similar dynamic programming approach to scan the array twice and get the larger value.


Java code:

public class Solution {
    public int rob(int[] nums) {
        if(nums.length == 0) {
            return 0;
        }
        if(nums.length == 1) {
            return nums[0];
        }
        if(nums.length == 2) {
            return Math.max(nums[0], nums[1]);
        }
        int len = nums.length;
        //include 1st element, and not last element
        int[] dp1 = new int[len-1];
        dp1[0] = nums[0];
        dp1[1] = Math.max(nums[0], nums[1]);
        for(int i = 2; i< len-1; i++) {
            dp1[i] = Math.max(dp1[i-1], dp1[i-2]+nums[i]);
        }
        //include last element, and not first element
        int[] dp2 = new int[len-1];
        dp2[0] = nums[1];
        dp2[1] = Math.max(nums[1], nums[2]);
        for(int i = 2; i < len-1; i++) {
            dp2[i] = Math.max(dp2[i-1], dp2[i-2] + nums[i+1]);
        }
        return Math.max(dp1[len-2], dp2[len-2]);
    }
}

Reference:

1. http://www.programcreek.com/2014/05/leetcode-house-robber-ii-java/

 

posted @ 2015-10-20 12:06  茜茜的技术空间  阅读(185)  评论(0编辑  收藏  举报