码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 213. House Robber II

时间:2016-06-25 21:36:54      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

Problem:    https://leetcode.com/problems/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.

 

Thought:

  Uses the code in House-robber, chooce the larger one between num[0] to num[n - 2] and num[1] to num[n - 1]

 

Code C++:

class Solution {
public:
    int rob(vector<int>& nums) {
        if (nums.size()==0)
            return 0;
        else if (nums.size() == 1)
            return nums[0];
        
        int n1 = 0,n2 = nums[0];
        for (int i = 1; i < nums.size() - 1; i++) {
            int temp = n1;
            n1 = n2;
            n2 = max(temp + nums[i], n2);
        }
        int pre = n2;
        
        n1 = 0,n2 = nums[1];
        for (int i = 2; i < nums.size(); i++) {
            int temp = n1;
            n1 = n2;
            n2 = max(temp + nums[i], n2);
        }
        int lat = n2;
        
        return max(pre,lat);
    }
};

 

LeetCode 213. House Robber II

标签:

原文地址:http://www.cnblogs.com/gavinxing/p/5616923.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!