[Leetcode]House Robber II

来源:互联网 发布:elf淘宝 编辑:程序博客网 时间:2024/06/04 23:27

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 arearranged 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 tonightwithout alerting the police.

class Solution {public:    /*algorithm: dp     for A[1..n],     dp(i) = max{dp(i-2) + A[i],dp(i-1)} if (start = 1, end = n-2)     dp(i) = max{dp(i-2) + A[i],dp(i-1) if(start = 2,end = n-1)    */    int getMax(vector<int>&nums,int start){         int n = nums.size();         int d0 = 0,d1 = 0,d2;         for(int i = start;i < n && i != (start-1+n)%n;i = (i+1)%n){            d2 = max(d0 + nums[i],d1);            d0 = d1;            d1 = d2;        }           return d1;    }    int rob(vector<int>& nums) {        int n = nums.size();        if(n == 1)return nums[0];        int max1 = getMax(nums,0);        int max2 = getMax(nums,1);        return max1 > max2?max1:max2;    }};


0 0
原创粉丝点击