House Robber 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.

思考,此問題的解跟House Robber有什麼關係

想法

  • 顯然,此問題的解不大於House Robber的解
  • 如果沒有搶劫最後一個house,則可以搶劫第1個house,如果搶劫了最後一個house,則第一個house不能劫。即無論如何此問題的解都在[0::n-1](搶劫了第一個)和[1::n](沒有搶劫第一個)中的一個最大的(PS:如果既沒有搶劫第一個也沒有搶劫最後一個,那麼這個解[0::n-1]和[1::n]都有包含)。

代碼

class Solution {
public:
    int help(vector<int> &a, int start, int end){
        int no = 0, yes = 0;
        for(int i = start; i < end; i++){
            int temp = yes;
            yes = max(yes, no + a[i]);
            no = max(no, temp);
        }
        return max(yes,no);
    }
    int rob(vector<int>& nums) {
        int n = nums.size();
        if(n == 0)
            return 0;
        if(n == 1)
            return nums[0];
        return max(help(nums,0,n - 1), help(nums,1,n));

    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章