leetcode——213——House Robber II

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.


class Solution {  
public:  
    int rob(vector<int> &nums) {  
       if (nums.size() == 0) return 0;
       if (nums.size() == 1) return nums[0];
       return max(robber(nums, 0, nums.size()-1), robber(nums, 1, nums.size()));

    }
    
    int robber(vector<int> &num,int start,int end)
    {
        int best0 = 0;   // 表示没有选择当前houses  
        int best1 = 0;   // 表示选择了当前houses  
        for(int i = start; i < end; i++){  
           int m = max(best1,best0+num[i]);  
            best0 = best1;   
            best1 = m;  
        }  
        return  best1;  
    }
};

你可能感兴趣的:(LeetCode)