首页 > 其他 > 详细

Leetcode House Robber II

时间:2015-10-20 13:55:50      阅读:260      评论:0      收藏:0      [点我收藏+]

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/

 

Leetcode House Robber II

原文:http://www.cnblogs.com/anne-vista/p/4894401.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!