213. House Robber II

来源:互联网 发布:下载天盾数据恢复软件 编辑:程序博客网 时间:2024/06/15 12:46

213. House Robber II           

Note: This is an extension ofHouse 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 arearranged 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 tonightwithout alerting the police.

        这个题和上一题house robber唯一的不同是,数列首位房子算是相邻。所以首位的房子不能同时出现,所以我们借用house robber的代码,分别对数列的[0,n-2]项和[1,n-1]项进行两次rob操作,所得的值取最大即是全局的最大值。

class Solution {public:int sub_rob(vector<int> &num, int p, int b) {int n = b - p + 1;int p1 = num[p], p2 = max(num[p], num[p + 1]);if (n < 2) return n ? num[p] : 0;else{for (int i = p + 2; i <= b; i++) {int m = max(p1 + num[i], p2);p1 = p2;p2 = m;}return p2;}}int rob(vector<int>& nums) {int n = nums.size();if (n < 2) return n ? nums[0] : 0;else return max(sub_rob(nums, 0, n - 2), sub_rob(nums, 1, n - 1));}};

0 0
原创粉丝点击