House Robber II

问题描述

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.

思考,此问题的解跟House Robber有什么关系

想法

  • 显然,此问题的解不大于House Robber的解
  • 如果没有抢劫最后一个house,则可以抢劫第1个house,如果抢劫了最后一个house,则第一个house不能劫。即无论如何此问题的解都在[0::n-1](抢劫了第一个)和[1::n](没有抢劫第一个)中的一个最大的(PS:如果既没有抢劫第一个也没有抢劫最后一个,那么这个解[0::n-1]和[1::n]都有包含)。

代码

class Solution {
public:
    int help(vector<int> &a, int start, int end){
        int no = 0, yes = 0;
        for(int i = start; i < end; i++){
            int temp = yes;
            yes = max(yes, no + a[i]);
            no = max(no, temp);
        }
        return max(yes,no);
    }
    int rob(vector<int>& nums) {
        int n = nums.size();
        if(n == 0)
            return 0;
        if(n == 1)
            return nums[0];
        return max(help(nums,0,n - 1), help(nums,1,n));

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值