您的位置:首页 > 其它

LeetCode House Robber II

2015-07-09 14:52 417 查看
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
[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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: