目录

题目描述:

你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。

示例 1:

输入: [2,3,2]
输出: 3
解释: 你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。

示例 2:

输入: [1,2,3,1]
输出: 4
解释: 你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。
     偷窃到的最高金额 = 1 + 3 = 4 。

解法:

class Solution {
public:
    // the houses form a cycle, thus, the best answer either rob the first house, or rob the last house, or neither
    int rob(vector<int>& nums) {
        int n = nums.size();
        if(n == 0){
            return 0;
        }else if(n == 1){
            return nums[0];
        }
        int pre = 0, cur = 0;
        int tmp = 0;
        for(int i = 0; i < n-1; i++){
            tmp = nums[i] + pre;    // rob i-th room
            pre = cur;
            cur = max(cur, tmp);
        }
        int res = cur;
        int pst = 0;
        cur = 0;
        for(int i = n-1; i > 0; i--){
            tmp = nums[i] + pst;    // rob i-th room
            pst = cur;
            cur = max(cur, tmp);
        }
        res = max(res, cur);
        return res;
    }
};
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄