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


解题思路:

Dynamic Programming.

这道题的本质相当于在一列数组中取出一个或多个不相邻数,使其和最大。

方法一:我们维护一个一位数组dp,其中dp[i]表示到i位置时不相邻数能形成的最大和,经过分析,我们可以得到dp[i] = Math.max(dp[i-1], dp[i-2]+num[i]).

方法二:核心思想还是用DP,分别维护两个变量a和b,然后按奇偶分别来更新a和b,这样就可以保证组成最大和的数字不相邻。We can use two variables, even and odd, to track the maximum value so far as iterating the array.

例: 50 1 1 50


Java code:

方法一:

public int rob(int[] nums) {
        if(nums.length == 0) {
            return 0;
        }
        if(nums.length == 1) {
            return nums[0];
        }
        int len = nums.length;
        
        int[] dp = new int[len];
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        for(int i = 2; i< len; i++) {
            dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i]);
        }
        return dp[len-1];
    }

方法二:

 public int rob(int[] nums) {
       if(nums.length == 0){
           return 0;
       }
       int even = 0;
       int odd = 0;
       for(int i = 0; i< nums.length; i++){
           if(i % 2 == 0){
               even += nums[i];
               even = Math.max(even, odd);
           }else {
               odd += nums[i];
               odd = Math.max(even, odd);
           }
       }
       return Math.max(even, odd);
    }

Reference:

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

2. http://www.cnblogs.com/grandyang/p/4383632.html

原文地址:https://www.cnblogs.com/anne-vista/p/4856686.html