LeetCode House Robber II

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


阅读更多
文章标签: java leetcode DP
个人分类: 算法/oj
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭