'lintcode 打劫房屋2'

描述

在上次打劫完一条街道之后,窃贼又发现了一个新的可以打劫的地方,但这次所有的房子围成了一个圈,这就意味着第一间房子和最后一间房子是挨着的。每个房子都存放着特定金额的钱。你面临的唯一约束条件是:相邻的房子装着相互联系的防盗系统,且 当相邻的两个房子同一天被打劫时,该系统会自动报警。

给定一个非负整数列表,表示每个房子中存放的钱, 算一算,如果今晚去打劫,在不触动报警装置的情况下, 你最多可以得到多少钱 。

样例

Example1

Input: nums = [3,6,4]
Output: 6
Example2

Input: nums = [2,3,2,3]
Output: 6

思路

首尾不能一起拿,那么分两次调用打劫房屋1的代码,一次是A[0] = 0, 一次是A[n-1] = 0,取最大值

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
/**
* @param nums: An array of non-negative integers.
* @return: The maximum amount of money you can rob tonight
*/
int houseRobber(vector &A) {
// write your code here
int n = A.size();
if (n == 0) return 0;
if (n == 1) return A[0];
if (n == 2) return max(A[0], A[1]);
vector res(n, 0);
res[n-1] = A[n-1];
res[n-2] = max(A[n-1], A[n-2]);
for (int i = n-3; i >= 0; i--)
res[i] = max(A[i] + res[i+2], res[i+1]);
return res[0];
}

int houseRobber2(vector &nums) {
// write your code here
if (nums.size() == 1) return nums[0];
vector temp1 = nums, temp2 = nums;
temp1[0] = 0;
temp2[nums.size() - 1] = 0;
return max(houseRobber(temp1),houseRobber(temp2));
}
};
-------------end of file thanks for reading-------------

你可能感兴趣的:('lintcode 打劫房屋2')