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.

 

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int take=0;
 5         int maxProfit=0;
 6         int nonTake=0;
 7 
 8         for(int i=0;i<nums.size();++i)
 9         {
10             take=nonTake+nums[i];
11             nonTake=maxProfit;
12             maxProfit=max(take,nonTake);
13         }
14 
15         return maxProfit;
16     }
17 };

 

II:

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.

 

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         if(nums.size()==1) return nums[0];
 5         return max(robbing(nums,0,nums.size()-1),robbing(nums,1,nums.size()));
 6     }
 7 
 8     int robbing(vector<int> &nums,int left,int right)
 9     {
10         int take=0;
11         int maxProfit=0;
12         int nonTake=0;
13         for(int i=left;i<right;i++)
14         {
15             take=nonTake+nums[i];
16             nonTake=maxProfit;
17             maxProfit=max(take,nonTake);
18         }
19 
20         return maxProfit;
21     }
22 };

 

posted on 2015-05-13 07:56  黄瓜小肥皂  阅读(137)  评论(0编辑  收藏  举报