「图解大厂面试高频算法题」链表专题-打家劫舍II
PS: 本文为「图解大厂面试高频算法题」专题,主旨是根据“二八法则”的原理,以付出20%的时间成本,获得80%的刷题的收益,让那些想进互联网大厂的人少走些弯路。
PS: 欢迎关注我获取更多大厂面试总结。
原题链接: https://leetcode-cn.com/problems/house-robber-ii/
题目介绍
题目解答
房子是一个环形,第一个房子与最后一个房子是相邻的,这意味着小偷如果偷了第一个房子的钱,就无法偷最后一个房子的钱,反之亦然。
如果我们对这个环进行简化,化简成一个按排进行排列的房子,那么我们只需要计算出
- 从第0到第N-1个房子中能偷取到的最大的金额
- 从第1到第N个房子中能偷取到的最大的金额
取 从第0到第N-1个房子中能偷取到的最大的金额 和 从第1到第N个房子中能偷取到的最大的金额 其中最大的一个金额,就是我们想要的答案。
化简之后的题目就变成算法好的人当小偷偷的钱都是最多的之动态规划打家劫舍I。如果没做过打家劫舍I的建议先阅读一下。
方法一:动态规划
代码实现
class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
if (nums.length == 2) {
return Math.max(nums[0], nums[1]);
}
return Math.max(rob(nums, 0, nums.length-2), rob(nums, 1, nums.length-1));
}
public int rob(int[] nums, int start, int end) {
int steal = nums[start], not_steal = 0;
for (int i = start+1; i <= end; i++) {
int new_steal = not_steal + nums[i];
int new_not_steal = Math.max(steal, not_steal);
steal = new_steal;
not_steal = new_not_steal;
}
return Math.max(steal, not_steal);
}
}
复杂度分析
- 时间复杂度:O(n),其中 n 是数组长度。只需要对数组遍历一次。
- 空间复杂度:O(1)。