You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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.
Example 1:
Input: [2,3,2] Output: 3 Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
Example 2:
Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
打家劫舍II。
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,能够偷窃到的最高金额。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/house-robber-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路依然是动态规划,但是这个题跟版本一的区别在于这个题是在一个环上操作,偷了第一个房子就不能投最后一个房子。为了简化过程,我们依然可以采用版本一的动态规划的思想但是对两个不同的数组进行计算,一个是包含了第一座房子,一个是包含了最后一座房子。其他思路基本和版本一没有差别。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int rob(int[] nums) { 3 // corner case 4 if (nums.length == 1) { 5 return nums[0]; 6 } 7 8 // normal case 9 int[] nums1 = Arrays.copyOfRange(nums, 1, nums.length); 10 int[] nums2 = Arrays.copyOfRange(nums, 0, nums.length - 1); 11 return Math.max(helper(nums1), helper(nums2)); 12 } 13 14 private int helper(int[] nums) { 15 int len = nums.length; 16 int[] dp = new int[len + 1]; 17 dp[0] = 0; 18 dp[1] = nums[0]; 19 for (int i = 2; i <= len; i++) { 20 dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]); 21 } 22 return dp[len]; 23 } 24 }
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var rob = function (nums) { 6 // corner case 7 if (nums === null || nums.length === 0) { 8 return 0; 9 } 10 if (nums.length === 1) { 11 return nums[0]; 12 } 13 // normal case 14 return Math.max(helper(nums.slice(1)), helper(nums.slice(0, -1))); 15 }; 16 17 var helper = function (nums) { 18 const dp = new Array(nums.length + 1).fill(0); 19 dp[0] = 0; 20 dp[1] = nums[0]; 21 for (let i = 2; i < dp.length; i++) { 22 dp[i] = Math.max(dp[i - 2] + nums[i - 1], dp[i - 1]); 23 } 24 return dp[nums.length]; 25 };