LeetCode House Robber
来源:互联网 发布:黑魂3 狼骑士大盾 数据 编辑:程序博客网 时间:2024/05/03 02:29
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.
思路分析:典型的动态规划,和求最大和子数组有点类似,global[i] 表示num[0...i]之间的最优解,那么DP方程可以写作global[i] = Max(global[i-2] + num[i], global[i-1]),分别对应于取num[i](此时不能取num[i-1])和不取num[i]的最优解,然后取max即可。是一个一维DP,时间和空间复杂度都是O(n)。
AC Code
public class Solution { public int rob(int[] num) { //1218 int n = num.length; if(n == 0) return 0; if(n == 1) return num[0]; int []global = new int [n]; global[0] = num[0]; global[1] = Math.max(num[0], num[1]); for(int i = 2; i < n; i++){ global[i] = Math.max(global[i-2] + num[i], global[i-1]);//Max(chooseNum[i], notChooseNum[i]) } return global[n-1]; //1224 }}优化后只有O(1)空间的代码如下,分别用a和b对奇数index和偶数index的数取local max,每次计算要更新全局max。
public int rob(int[] num) { if(num == null || num.length == 0) return 0; int a = 0; //odd int b = 0; //even for(int i = 0; i < num.length; i++){ if(i%2 == 0){ b += num[i]; b = Math.max(a, b); } else{ a += num[i]; a = Math.max(a, b); } } return Math.max(a,b); }
- 【dp】Leetcode House Robber&& House Robber II
- 【leetcode】House Robber && House Robber II
- LeetCode --- House Robber & House Robber II
- LeetCode OJ House Robber
- Leetcode: House Robber
- Leetcode 198: House Robber
- House Robber - LeetCode
- LeetCode 之 House Robber
- leetcode--House Robber
- [leetcode]47 House Robber
- [LeetCode] House Robber
- LeetCode :House Robber
- [leetcode] House Robber
- [leetcode]House Robber
- [LeetCode]198.House Robber
- LeetCode House Robber题解
- leetcode:House Robber
- [LeetCode]House Robber
- Josephus problem(输出Josephus序列)
- iOS开发中,通讯录去除空格的方法
- Oracle db规范之 删除oracle 归档日志之前的几个检查项
- java 反射技术
- redis命令
- LeetCode House Robber
- 对话框的伸缩
- UVa 378 - Intersecting Lines
- week8---4月23日
- HDU1814.Peaceful Commission——2-sat输出字典序最小的解
- Step into Scala - 03 - 变量,常量与表达式
- error C2137:空字符常量
- Supercomputers Materials
- Air strike II BFS+DFS