LeetCode: 213. House Robber II

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);
    }
};
全部评论

相关推荐

07-11 11:15
中南大学 Java
好可爱的hr姐姐哈哈哈哈
黑皮白袜臭脚体育生:兄弟们貂蝉在一起,吕布开了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务