[leetcode]213. House Robber II

来源:互联网 发布:软件采购招标评分标准 编辑:程序博客网 时间:2024/06/18 06:35

题目链接:https://leetcode.com/problems/house-robber-ii/#/description

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.


思路:由于第一家和最后一家相连,所以第一家和最后一家不能同时抢,那么我们分别把第一家和最后一家去掉,取最大值。

class Solution{public:    int rob(vector<int>& nums)    {        if (nums.size() <= 1) return nums.empty() ? 0 : nums[0];        vector<int> res1(nums.size()-1,0);        vector<int> res2(nums.size()-1,0);        for(int i=0;i<nums.size()-1;i++)        {            if(i==0)                res1[i]=max(0,nums[i]);            else                res1[i]=max(res1[i-1],res1[i-2]+nums[i]);        }        for(int i=0;i<nums.size()-1;i++)        {            if(i==0)                res2[i]=max(0,nums[i+1]);            else                res2[i]=max(res2[i-1],res2[i-2]+nums[i+1]);        }        return max(res1[nums.size()-2],res2[nums.size()-2]);    }};


0 0