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

LintCode 392 House Robber

时间:2016-12-22 06:56:28      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:nbsp   ace   for   lint   tmp   ber   return   lin   tco   

// Ref: https://segmentfault.com/a/1190000003811581
// Ref: http://www.cnblogs.com/grandyang/p/4383632.html

/*
如果选择了抢劫上一个屋子,那么就不能抢劫当前的屋子,所以最大收益就是抢劫上一个屋子的收益
如果选择抢劫当前屋子,就不能抢劫上一个屋子,所以最大收益是到上一个屋子的上一个屋子为止的最大收益,加上当前屋子里有的钱
*/

 1 public static long houseRobber(int[] A) {
 2         int len = A.length;
 3         if (len <= 1) {
 4             return len == 0 ? 0: A[0];
 5         }
 6 
 7         long previous = A[0]; // a is the previous max
 8         long current = Math.max(A[0], A[1]); // b is the current max
 9         for(int i = 2; i < len; i++){
10             long tmp = current;
11             // previous + A[i] => pre-pre + current
12             // b/c it cannot rob adjacent houses => need to compare
13             current = Math.max(previous + A[i], current);
14             previous = tmp;
15         }
16         return current;
17     }

 

LintCode 392 House Robber

标签:nbsp   ace   for   lint   tmp   ber   return   lin   tco   

原文地址:http://www.cnblogs.com/wenchan/p/6209645.html

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