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.

Solution:

int rob(vector<int>& nums) {
    if(nums.empty()) return 0;
    int n = nums.size();
    if(n == 1) return nums[0];
    return max(rob_util(nums, 1, n-1), rob_util(nums, 0, n-2));
}

int rob_util(vector<int>& nums, int start, int end) {
    int now = 0, prev = 0;
    for(int i=start; i<=end; i++) {
        int tmp = now;
        now = max(now, nums[i]+prev);
        prev = tmp;
    }
    return now;
}

猜你喜欢

转载自yuanhsh.iteye.com/blog/2214434
今日推荐