您的位置:首页 > 其它

LeetCode 198-House Robber

2015-06-02 21:46 197 查看
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.

题目解析:该题就是说给你连续的一串数,取得每一个数至少有一个间隔,找出所取得数之和所能达到的最大值?

该题的关键点在于由少至多慢慢增加,当只有一个数的时候自然是temp[0]最大,两个时候和就是temp[0]、temp[1]中大的哪一个,三个的时候就是看temp[0]+tem[2]与temp[1]谁大,比较出来后,可以将0和2的和合并,等3进来后,任然只有(temp)1、2、3三个元素.

代码
public class Solution {
    public int rob(int[] nums) {
	    	int[] temp=nums;
	    	if(temp.length==0)return 0;
	    	if(temp.length==1)return temp[0];
	    	if(temp[1]<temp[0])temp[1]=temp[0];
	    	for(int i=2;i<temp.length;i++){
	    		if((temp[i]+temp[i-2])<temp[i-1])
	    		{
	    			temp[i]=temp[i-1];
	    					
	    		}else{
	    			temp[i]=temp[i]+temp[i-2];
	    		}
	    	}
			return temp[temp.length-1];
	        
	    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: