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])
代码如下:
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]); }
相关文章推荐
- LeetCode 198. House Robber
- LeetCode 198. House Robber【DP+滚动数组】
- 【LeetCode】198. House Robber
- leetcode198. House Robber
- [leetcode] 198. House Robber
- LeetCode-198. House Robber (JAVA)寻找数组不相邻组合最大值DP
- 【LeetCode题解】198. House Robber
- 【LeetCode】 198. House Robber
- [LeetCode]198. House Robber I&II
- LeetCode 198. House Robber
- LeetCode 198. House Robber
- LeetCode 198. House Robber
- LeetCode198. House Robber
- LeetCode 198. House Robber
- [LeetCode]198. House Robber (JavaScript)
- LeetCode 198. House Robber
- 2017.12.18 LeetCode - 198. House Robber【dp入门】
- LeetCode198. House Robber
- LeetCode 198. House Robber
- [LeetCode]198. House Robber