# LeetCode House Robber II

119人阅读 评论(0)

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:

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;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：67417次
• 积分：3301
• 等级：
• 排名：第10617名
• 原创：288篇
• 转载：0篇
• 译文：0篇
• 评论：4条
文章分类
阅读排行
最新评论