213. House Robber II

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.

题意:假设所有的房子都相连组成一个圈,仍然不能取相邻的房子,那么最大收益为如何。

思路:原先房子是一列,则动态规划求解出最大值,现在房子是一个圈,则第1个房子和第n个房子不能同时取,那么问题就分为两大类,有1没n的时候最大值,和有n没1的时候的最大值,即求出sum(0, n-2)与sum(1, n-1)并比较大小即可。

class Solution {
public:
	int rob(vector<int>& nums) {
		if (nums.empty()){
			return 0;
		}
		int length = nums.size();
		if (length == 1)
			return nums[0];

		//calaulate 0 to n-2
		vector<int> f(length, 0);
		f[1] = nums[0];
		for (int i = 2; i < length; i++){
			f[i] = max(f[i - 1], f[i - 2] + nums[i - 1]);
		}
		
		if (length == 2)
			return max(nums[0], nums[1]);
		//calculate 1 to n-1
		vector<int> g(length, 0);
		g[1] = nums[1];
		for (int i = 2; i < length; i++){
			g[i] = max(g[i - 1], g[i - 2] + nums[i]);
		}

		return max(f[length - 1], g[length - 1]);
	}
};






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值