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

相关推荐

程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
no_work_no_life:深圳,充电宝,盲猜anker
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务