2025-07-25 18:23:29 +08:00

42 lines
1.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package dynamic_programming;
/**
* 题目: 213. 打家劫舍 II (rob)
* 描述:你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
* 给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,今晚能够偷窃到的最高金额。
*
示例 2
输入nums = [2,3,2]
输出3
解释:你不能先偷窃 1 号房屋(金额 = 2然后偷窃 3 号房屋(金额 = 2, 因为他们是相邻的。
* 链接https://leetcode.cn/problems/house-robber-ii/
*/
//二刷会做
public class Rob2 {
public int rob(int[] nums) {
int n = nums.length;
if (n == 0) return 0;
if (n == 1) return nums[0];
// 情况二:不抢最后一家,抢 [0..n-2]
int result1 = robRange(nums, 0, n - 2);
// 情况三:不抢第一家,抢 [1..n-1]
int result2 = robRange(nums, 1, n - 1);
return Math.max(result1, result2);
}
// 198. 打家劫舍 的逻辑,区间 [start..end]
private int robRange(int[] nums, int start, int end) {
if (start == end) {
return nums[start];
}
// dp 大小和 nums 一致,直接复用索引
int[] dp = new int[nums.length];
dp[start] = nums[start];
dp[start + 1] = Math.max(nums[start], nums[start + 1]);
for (int i = start + 2; i <= end; i++) {
dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
}
return dp[end];
}
}