24.House Robber (DP)

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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

分析:这个题目是典型的动态规划的题目。类似的题目是求不相邻元素的数组的最大和

首先我们可以假设出前(i-1)个房子已经偷盗完毕。其中t1表示偷了第(i-1)家得到的最大收益,t2表示没有偷第(i-1)家得到的最大收益。

则对于第i家,如果偷该家可以得到的最大收益为t2+nums[i];如果不偷该家可以得到的最大收益是Math.max(t1,t2)。

最后对于第n家,可以计算得到其对应的t1,t2只需返回两者中的较大值即可。

public int rob(int[] nums) {
		if(nums.length == 0){
			return 0;
    	}else{
    		if(nums.length  == 1){
    			return nums[0];
    		}else{
    			int t1 =nums[0];//以nums[i-1]结尾的最大值
    			int t2 =0;//不以nums[i-1]结尾的最大值
    			for(int i=1;i<nums.length;i++){
    					int temp1 = t1;
    					int temp2 = t2;
    					t1 = temp2+nums[i];//以nums[i]结尾的最大值
    					t2 = Math.max(temp1, temp2);//不以nums[i]结尾的最大值
    			}
    			if(t1>t2){
    				return t1;
    			}else{
    				return t2;
    			}
    		}
    	}
    }




你可能感兴趣的:(24.House Robber (DP))