LeetCode: 213. House Robber II

版权声明:本文由博主@杨领well发表在http://blog.csdn.net/yanglingwell,如果转载请注明出处。 https://blog.csdn.net/yanglingwell/article/details/82875804

LeetCode: 213. House Robber II

题目描述

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

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.

Example 1:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.

Example 2:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

解题思路

参考 LeetCode: 198. House Robber 题解,计算区间 [0, size-1)(不偷最后一间) 和 [1, size) (不偷第一间)的最大值。

AC 代码

class Solution {
public:
    // [beg, end)
    int rob(vector<int>& nums, int beg, int end) {
        // first:  当前房间不偷的最大收益
        // second: 偷当前房间的最大收益
        pair<int, int> lastHouse{0, 0}; 
        pair<int, int> curHouse{0, 0}; 
        
        for(size_t i = beg; i < end; ++i)
        {
            // 当前房间不偷:上一间房间不偷的最大收益和上间房间偷的最大收益的最大值
            curHouse.first = max(lastHouse.second, lastHouse.first);
            // 偷当前房间:不偷上一间房间的最大收益加上偷当前房间的收益
            curHouse.second = lastHouse.first + nums[i];
            
            lastHouse = curHouse;
        }
        
        return max(curHouse.first, curHouse.second);
    }
    
    int rob(vector<int>& nums)
    {
        if(nums.empty())
        {
            return 0;
        }
        else if(nums.size() == 1)
        {
            return nums[0];
        }
        
        int moneyFirstRob = rob(nums, 0, nums.size()-1);
        int moneyLastRob = rob(nums, 1, nums.size());
        
        return max(moneyFirstRob, moneyLastRob);
    }
};

猜你喜欢

转载自blog.csdn.net/yanglingwell/article/details/82875804
今日推荐