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

House Robber II

时间:2015-09-15 07:00:32      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street. 

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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

 

Runtime: 0ms

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int n = nums.size();
 5         if(n == 0) return 0;
 6         if(n == 1) return nums[0];
 7         if(n == 2) return max(nums[0], nums[1]);
 8         
 9         int *dp1 = new int[n];
10         dp1[0] = nums[0];
11         dp1[1] = nums[0];
12         //rub the first house
13         for(int i = 2; i < n - 1; i++){
14             dp1[i] = max(dp1[i -2] + nums[i], dp1[i - 1]);
15         }
16         dp1[n - 1] = dp1[n - 2];
17         
18         //do not rub the first house
19         int *dp2 = new int[n];
20         dp2[0] = 0;
21         dp2[1] = nums[1];
22         for(int i = 2; i < n; i++){
23             dp2[i] = max(dp2[i - 2] + nums[i], dp2[i - 1]);
24         }
25         
26         return max(dp1[n - 1], dp2[n -1]);
27     }
28 };

 

House Robber II

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4809043.html

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