【题目】
I
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.
IIAfter 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.
【解析】I:一条直线上有n座房子,每座房子里都有一定的现金(用nums[i]表示),不能同时抢劫相邻的两座房子,问最多能抢劫多少钱?这是一道典型的动态规划,用money[i]表示从第1座房子到第i座房子能抢到的最多的钱,那么money[i] = max(money[i - 2] + nums[i], money[i - 1])。
II:一个圆上有n座房子,其它条件都一样,只是第1座房子和第n座房子变成相邻的了,也就是说不能同时抢了,那么最优解就变成 第1座房子到第n-1座房子能抢的最多的钱 或者 第2座房子到第n座房子能抢的钱了。
【I 的解法】
public class Solution { // O(n)空间的写法 public int rob1(int[] num) { if (num.length == 0) return 0; int[] dp = new int[num.length + 1]; dp[0] = 0; dp[1] = num[0]; for (int i = 2; i <= num.length; i++) { dp[i] = Math.max(dp[i - 1], dp[i - 2] + num[i - 1]); } return dp[num.length]; } // O(1)空间的写法 public int rob(int[] num) { if (num.length == 0) return 0; int prepre = 0; int pre = num[0]; for (int i = 1; i < num.length; i++) { int cur = Math.max(prepre + num[i], pre); prepre = pre; pre = cur; } return pre; } }
【II 的解法】
public class Solution { public int rob(int[] nums) { int n = nums.length; if (n == 0) return 0; if (n == 1) return nums[0]; return Math.max(robBetween(nums, 0, n - 2), robBetween(nums, 1, n - 1)); } public int robBetween(int[] nums, int start, int end) { int prepre = 0; int pre = nums[start]; for (int i = start + 1; i <= end; i++) { int cur = Math.max(prepre + nums[i], pre); prepre = pre; pre = cur; } return pre; } }