【LeetCode】House Robber

来源:互联网 发布:js给div添加class属性 编辑:程序博客网 时间:2024/06/15 11:28
【问题描述】

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.


这道题其实就是给定一个数组,找出不相邻的数累加和最大。因此,这是一道标准的动态规划问题,具体如下:

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

0 0