package OCT._213;
/*
213. 打家劫舍 II 不会
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,
这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,
如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,今晚能够偷窃到的最高金额。
输入:nums = [2,3,2]
输出:3
解释:你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。
假设数组 nums 的长度为 nn。如果不偷窃最后一间房屋,则偷窃房屋的下标范围是 [0,n−2];
如果不偷窃第一间房屋,则偷窃房屋的下标范围是 [1,n−1]。
在确定偷窃房屋的下标范围之后,即可用第 198 题的方法解决。
对于两段下标范围分别计算可以偷窃到的最高总金额,其中的最大值即为在 nn 间房屋中可以偷窃到的最高总金额。
*/
public class Test01 {
}
class Solution {
public int rob(int[] nums) {
int length = nums.length;//数组的长度
//和之前的情况一模一样,就是有一点不一样,在偷最后一间的时候,必须考虑第一间房子的情况
if (length == 0) {
return 0;
}
if (length == 1) {
return nums[0];
}
if (length == 2) {
return Math.max(nums[0], nums[1]);
}
//房间数大于0的情况,分两种情况来讨论
//第一种是不考虑第一间房子
//第二种是不考虑最后一间房子
int[] profits1 = new int[length-1];
int[] profits2 = new int[length-1];
//从1 2 3 到 n-1 nums[n] 不考虑第一间房子
profits1[0] = nums[1];
profits1[1] = Math.max(nums[1], nums[2]);
for (int i = 3; i < length; i++) {
profits1[i-1] = Math.max(nums[i] + profits1[i - 3], profits1[i - 2]);
}
//从0 1 2 3 到 n-2 nums[n] 不考虑最后一间房子
profits2[0] = nums[0];
profits2[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < length-1; i++) {
profits2[i] = Math.max(nums[i] + profits2[i - 2], profits2[i - 1]);
}
return Math.max(profits1[length - 2], profits2[length - 2]);
}
}
/*
考虑到每间房屋的最高总金额只和该房屋的前两间房屋的最高总金额相关,因此可以使用滚动数组,在每个时刻只需要存储前两间房屋的最高总金额,将空间复杂度降到 O(1)O(1)。
*/
class Solution2 {
public int rob(int[] nums) {
int length = nums.length;
if (length == 1) {
return nums[0];
} else if (length == 2) {
return Math.max(nums[0], nums[1]);
}
return Math.max(robRange(nums, 0, length - 2), robRange(nums, 1, length - 1));
}
public int robRange(int[] nums, int start, int end) {
int first = nums[start], second = Math.max(nums[start], nums[start + 1]);
for (int i = start + 2; i <= end; i++) {
int temp = second;
second = Math.max(first + nums[i], second);
first = temp;
}
return second;
}
}
213. 打家劫舍 II
最新推荐文章于 2024-06-30 22:10:28 发布