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.
这道题的重点就是在于要在不能将相邻两个house里的钱相加的情况下计算出所有的house里可相加的钱的最大值。
个人觉得比较简单的方法就是设定两个变量,一个previousrobbed,一个perviousdidntrob,因为我们在考虑是否add这个house的money的时候必须要考虑它相邻的之前的那个house有木有被breakin。
同样还有一些情况,比如这个house被rob了,它后面连着两个house也是可以都不被rob的,因此我们又需要需要用到Math.max()method了。
代码如下。~
public class Solution { public int rob(int[] nums) { if(nums==null||nums.length==0){ return 0; } int didrob=0; int dontrob=0; for(int i=0;i