213. House Robber II
Problem:
Solution:
第二遍实现感觉编码能力提升太多。
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.
Analysis:
把first 和last element分别去掉求house robber。然后取2个house robber的最大值。实现houseRobber花了点时间,因为start和end是动态的。记住一点就好,在循环里面F[i%2]的第一个肯定是i%2==0。这样一开始的i就必须是2,不能是动态的。Solution:
第二遍实现感觉编码能力提升太多。
class Solution { public int rob(int[] nums) { if (nums == null || nums.length == 0) return 0; if (nums.length() == 1) return nums[0]; return Math.max(helper(nums, 2, nums.length), helper(nums, 1, nums.length - 1)); } private int helper(int[] nums, int start, int end) { int[] dp = new int[nums.length + 1]; dp[start - 1] = 0; dp[start] = nums[start - 1]; for (int i = start + 1; i <= end; i++) { dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]); } return dp[end]; } }
评论
发表评论