LeetCode——House Robber

Description:

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.

求数组中不相邻两个数组合的最大值。

ps.难道这就是传说中的DP

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[] res = new int[nums.length];
        res[0] = nums[0];
        res[1] = nums[1];
        res[2] = nums[0] + nums[2];
        for(int i=3; i<nums.length; i++) {
            res[i] = Math.max(res[i-2],res[i-3]) + nums[i];
        }
        return Math.max(res[nums.length-1], res[nums.length-2]);
    }
}
原文地址:https://www.cnblogs.com/wxisme/p/4596620.html