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

[LeetCode] House Robber II

时间:2015-08-15 11:43:56      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

This problem is a little tricky at first glance. However, if you have finished the House Robberproblem, this problem can simply be decomposed into two House Robber problems. Suppose there are n houses, since house 0 and n - 1 are now neighbors, we cannot rob them together and thus the solution is now the maximum of

  1. Rob houses 0 to n - 2;
  2. Rob houses 1 to n - 1.

The code is as follows. Some edge cases (n <= 2) are handled explicitly.

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int n = nums.size();
 5         if (n <= 2) return n ? (n == 1 ? nums[0] : max(nums[0], nums[1])) : 0;
 6         return max(robber(nums, 0, n - 2), robber(nums, 1, n -1));
 7     }
 8 private:
 9     int robber(vector<int>& nums, int l, int r) {
10         int pre = 0, cur = 0;
11         for (int i = l; i <= r; i++) {
12             int temp = max(pre + nums[i], cur);
13             pre = cur;
14             cur = temp;
15         } 
16         return cur;
17     }
18 };

 

[LeetCode] House Robber II

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4732035.html

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