您的位置:首页 > 其它

Leetcode 198. House Robber

2017-07-10 15:03 323 查看
问题描述

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.

问题分析:题目要求没有相邻两个数同时被选择的最大总收益。

保留两个数组,一个数组dprob[i]表示在第i个选择的条件下前i个数的最大收益,dpnrob[i]表示第i个不选择的条件下前i个数的最大收益。状态转移矩阵:

dprob[i]=dpnrob[i-1]+nums[i];

dpnrob[i]=max(dprob[i-1],dpnrob[i-1])

代码如下:

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