[Leetcode] House Robber

来源:互联网 发布:应用程序端口号 编辑:程序博客网 时间:2024/05/17 04:03

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) {        if(nums.length<1) return 0;        int sum1=nums[0];        int sum2=nums[0];        int sum3=0;        int len=nums.length;        if(nums.length==1) return sum1;        int lastnumberselected=0;        if((nums[1]-nums[0])>0)         {            lastnumberselected=1;            sum2=nums[1];        }        if(nums.length==2) return sum2;        for(int i=2;i<len;i++)        {            if(lastnumberselected==0)             {                sum3=sum2+nums[i];                lastnumberselected=1;            }            else if((sum1+nums[i])<sum2) sum3=sum2;                 else                  {                     sum3=sum1+nums[i];                    lastnumberselected=1;                 }            sum1=sum2;            sum2=sum3;        }        return sum3;    }}



0 0