Skip to content

Latest commit

 

History

History
54 lines (32 loc) · 1023 Bytes

File metadata and controls

54 lines (32 loc) · 1023 Bytes

### 解题思路

The key of this problem is we will never miss the i-3 or i-2 position house when we deciside rob i

dp[i] 到位置i为末尾能抢到的最多钱

dp[i] = max(dp[i-3], dp[i-2]) + nums[i]

marginal conditions:

​ dp[0] = nums[0];

​ dp[1] = nums[1];

​ dp[2] = nums[0] + nums[2];

### 代码

class Solution {
    public int rob(int[] nums) {
        int[] dp = new int[nums.length];
        // dp[i] 到位置i为末尾能抢到的最多钱
        // dp[i] = max(dp[i-3], dp[i-2]) + nums[i] 
        int numsLength = nums.length;
        if (numsLength == 1){
            return nums[0];
        }

        if (numsLength == 2){
            return Math.max(nums[0], nums[1]);
        }

        dp[0] = nums[0];
        dp[1] = nums[1];
        dp[2] = nums[0] + nums[2];

        for (int i=3; i < numsLength; i++){
            dp[i] = Math.max(dp[i-3], dp[i-2]) + nums[i];
        }

        return Math.max(dp[numsLength-1], dp[numsLength-2]);




    }
}