码迷,mamicode.com
首页 > 其他好文 > 详细

House Robber

时间:2017-05-10 14:31:46      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:return   提示   rmi   connected   ted   represent   can   color   for   

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

标签:return   提示   rmi   connected   ted   represent   can   color   for   

原文地址:http://www.cnblogs.com/xinqiwm2010/p/6835414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!