首页 > 代码库 > House Robber
House Robber
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.
Example
Given [3, 8, 4]
, return 8
.
一开始用了一个一位数组做DP, 后来看了提示用两个变量即可,降低了空间复杂度
1 public class Solution { 2 /** 3 * @param A: An array of non-negative integers. 4 * return: The maximum amount of money you can rob tonight 5 */ 6 public long houseRobber(int[] A) { 7 // write your code here 8 if(A==null||A.length==0) return 0; 9 10 long f1 = 0; 11 long f2 = 0; 12 13 for(int i=1;i<=A.length;i++){ 14 long temp1=f1; 15 f1 = Math.max(f1, f2+A[i-1]); 16 f2=temp1; 17 } 18 return f1; 19 } 20 }
House Robber
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。