LeetCode House Robber

198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

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.

方法

dp[n]表示在前n个最多抢多少钱, dp[i] = Math.max(dp[i-2]+nums[i],dp[i-1]) (i >= 2)

public class Solution {
    public int rob(int[] nums) {
        //dp表示走过前n家投了多少
        int[] dp = new int[nums.length];
        if(nums.length <= 0){
            return 0;
        }
        if(nums.length == 1){
            return nums[0];
        }
        if(nums.length == 2){
            return Math.max(nums[0],nums[1]);
        }
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0],nums[1]);
        for(int i = 2; i < nums.length; i++){
            dp[i] = Math.max(dp[i-2]+nums[i],dp[i-1]);
        }
        return dp[nums.length-1];
    }
}

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.

方法

由于成环状,即收尾不能相邻。实际上可以把情况分为两种讨论,即0->length-2和1->length-1,选择其中的最大值输出,从而避免了收尾相邻的情况。

public class Solution {
    public int rob(int[] nums) {
        return Math.max(chooseRob(nums,0,nums.length-2),chooseRob(nums,1,nums.length-1));
    }
    public int chooseRob(int[] nums, int start, int end){
        int[] dp = new int[nums.length];
        if(nums.length <= 0){
            return 0;
        }
        if(nums.length == 1){
            return nums[0];
        }
        if(nums.length == 2){
            return Math.max(nums[0],nums[1]);
        }
        dp[start] = nums[start];
        dp[start+1] = Math.max(nums[start],nums[start+1]);

        for(int i = start+2; i <= end; i++){
            dp[i] = Math.max(dp[i-2] + nums[i],dp[i-1]);
        }
        return dp[end];
    }
}
Share