LeetCode House Robber II

原创 2015年07月09日 14:52:11

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.

Solution:

固定第一个点, 然后从第二个点开始dp即可。

import java.util.*;

public class Solution {
	public int rob(int[] nums) {
		int n = nums.length;
		if (n == 0)
			return 0;
		int dp[][] = new int[n][2];

		if (n == 1)
			return nums[0];

		dp[0][0] = 0;
		dp[0][1] = nums[0];

		dp[1][0] = 0;
		dp[1][1] = nums[1];
		for (int i = 2; i < n; i++) {
			dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);
			dp[i][1] = dp[i - 1][0] + nums[i];
		}
		int max = Math.max(dp[n - 1][0], dp[n - 1][1]);

		dp[1][0] = nums[0];
		dp[1][1] = nums[1];
		for (int i = 2; i < n; i++) {
			dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);
			dp[i][1] = dp[i - 1][0] + nums[i];
		}
		max = Math.max(max, dp[n - 1][0]);

		return max;
	}
}


相关文章推荐

<LeetCode OJ> (198 / 213) House Robber(I / II)

House Robber My Submissions Question Total Accepted: 45702 Total Submissions: 142460 Difficulty:...

[leetcode 213]House Robber II

Note: This is an extension of House Robber. After robbing those houses on that street, the thief ha...

leetcode - 198,213. House Robber(II) & 91. Decode Ways

算法系列博客之Dynamic Programming 本篇博客将运用动态规划的思想来解决leetcode上198和213号问题 问题描述:198 House RobberYou are a pr...
  • Quiteen
  • Quiteen
  • 2017年06月11日 15:09
  • 87

LeetCode House Robber I and II

在这里,我将这两题放在一起来解决,因为这两道都是在Dynamic Programming(动态规划)的类型里面,所以放在一起比较好,只是第二题比第一题多了一个条件,其他都是一样的。 首先是第一题: ...

[LeetCode] House Robber II 求循环数组中元素两两不相邻的子序列最大和

声明:原题目转载自LeetCode,解答部分为原创 Problem :     Note: This is an extension of House Robber. [LeetCode] ...
  • xblog_
  • xblog_
  • 2017年06月12日 16:28
  • 88

Leetcode 213 House Robber II 抢劫最大金额

HouseRobber扩展:抢劫完那条街道上的房子之后,这个贼有找到了实施自己盗窃行动的另一个地点,这样他才不会引来太多注意。这次,这里的搜有房子排成了一个圆圈,这意味着第一个房子和最后一个房子也是挨...

leetcode 213. House Robber II

After robbing those houses on that street, the thief has found himself a new place for his thievery ...

LeetCode No.213 House Robber II

LeetCode No.213 House Robber II

LeetCode-213. House Robber II

Note: This is an extension of House Robber. After robbing those houses on that street, the thief ha...

leetcode--House Robber II

House Robber II
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode House Robber II
举报原因:
原因补充:

(最多只允许输入30个字)