198. House Robber

来源:互联网 发布:义乌淘宝培训多少钱 编辑:程序博客网 时间:2024/05/20 21:45

You are a professional robber planning torob 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 adjacenthouses have security system connected and it will automatically contact thepolice if two adjacent houses were broken into on the same night.

Given a list of non-negative integersrepresenting the amount of money of each house, determine the maximum amount ofmoney you can rob tonight without alerting the police.

    翻译:你是一个专业的强盗计划抢一条街的房子。 每个房子都有一定金额的钱,唯一的约束,阻止你抢劫他们是相邻的房子有安全系统连接,如果两个相邻的房子被打破在同一个夜晚,它会自动联系警察。

给出一个表示每个房子的钱数的非负整数列表,确定你今晚可以抢夺的最大金额,而不警告警察。

    分析:就是说给出一个整数数组,看如何选取值保证总和最大,但是不能取相邻的两个元素的值。这题跟以前写过的走楼梯和子串的最大和类似,也是一种动态规划的思想。当前数a[i]只有两种情况,选择和不选择;选择时,则为max[i-2]+1[i],不选择则是max[i-1]最大。因此可以写出:

max[0]=a[0];

max[1]=max[1];

当i>=2时,max[i]=max(max[i-1]+a[i],max[i-1]);

    同时还需要考虑数组的长度等一些特殊返回值。

    具体代码如下:

public class Solution {

   public int rob(int[] nums) {

       if(nums.length==0) return 0;

        if(nums.length==1) return nums[0];

       int max[]=new int[nums.length];

            max[0]=nums[0];//当前的最大值

            max[1]=Math.max(nums[0],nums[1]);

            for(int i=2;i<nums.length;i++){

                  max[i]=Math.max(max[i-2]+nums[i],max[i-1]);

            }

            return max[nums.length-1];

    }

}

 

0 0
原创粉丝点击