LeetCode House Robber II

来源:互联网 发布:苹果铃声制作软件 编辑:程序博客网 时间:2024/05/23 18:34

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


0 0
原创粉丝点击