1. 程式人生 > >演算法訓練:House Robber II

演算法訓練:House Robber II

    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()-2), robber(nums, 1, nums.size()-1));
    }
    int robber(vector<int> &nums, int start, int end) {
        int n = end-start + 1;  
        vector<int> sum(n,0);  
        sum[0] = nums[start];  
        sum[1] = max(nums[start], nums[start+1]);  
          
        for(int i=2; i<n; i++) {  
            sum[i] = max(sum[i-2]+nums[start+i], sum[i-1]);  
        }  
        return sum[n-1]; 
    }