前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 213 House Robber II

Leetcode 213 House Robber II

作者头像
triplebee
发布2018-01-12 14:44:26
5880
发布2018-01-12 14:44:26
举报
文章被收录于专栏:计算机视觉与深度学习基础

Note: This is an extension of House Robber.

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.

抢劫犯的第二题,第一题题解链接 https://cloud.tencent.com/developer/article/1019125

与第一题不同在于这次是一个换,首尾不能同时抢。

那么可以变通一下,将这个问题转化为0-n-2下标和1-n-1下标两个子问题的最大值问题。

这样就可以保证首尾不会同时被抢,相当于做了两次抢劫犯第一题的过程。

代码语言:javascript
复制
class Solution {
public:
    int rob(vector<int>& nums) {
        int a1 = 0;
        int b1 = 0;
        int a2 = 0;
        int b2 = 0;
        if(nums.size() == 1) return nums[0];
        for(int i = 0; i < nums.size(); i++)
        {
            if(i != nums.size() - 1)
            {
                if(i & 1) a1 = max(a1 + nums[i], b1);
                else b1 = max(b1 + nums[i], a1);
            }
            if(i != 0)
            {
                if(i & 1) a2 = max(a2 + nums[i], b2);
                else b2 = max(b2 + nums[i], a2); 
            }
        }
        return max(max(a1, b1), max(a2, b2)); 
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-03-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档