House Robber II 解答

Question

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

Key to this problem is to break the circle. So we can consider two situations here:

1. Not include last element

2. Not include first element

Therefore, we can use the similar dynamic programming approach to scan the array twice and get the larger value.

 1 public class Solution {
 2     public int rob(int[] nums) {
 3         if (nums == null || nums.length < 1)
 4             return 0;
 5         int length = nums.length, tmp1, tmp2;
 6         if (length == 1)
 7             return nums[0];
 8         int[] dp = new int[length];
 9         dp[0] = 0;
10         dp[1] = nums[0];
11         // First condition: include first element, not include last element;
12         for (int i = 2; i < length; i++)
13             dp[i] = Math.max(dp[i - 1], nums[i - 1] + dp[i - 2]);
14         tmp1 = dp[length - 1];
15         // Second condition: include last element, not include first element;
16         dp = new int[length];
17         dp[0] = 0;
18         dp[1] = nums[1];
19         for (int i = 2; i < length; i++)
20             dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]);
21         tmp2 = dp[length - 1];
22         return tmp1 > tmp2 ? tmp1 : tmp2;
23     }
24 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4822577.html