当前位置:网站首页>Leetcode 213: 打家劫舍 II
Leetcode 213: 打家劫舍 II
2022-07-03 07:21:00 【会学习的朱丫】
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,今晚能够偷窃到的最高金额。
思路
这道题目和198.打家劫舍是差不多的,唯一区别就是成环了。
对于一个数组,成环的话主要有如下三种情况:
- 情况一:考虑不包含首尾元素
- 情况二:考虑包含首元素,不包含尾元素
- 情况三:考虑包含尾元素,不包含首元素
注意我这里用的是"考虑",例如情况三,虽然是考虑包含尾元素,但不一定要选尾部元素! 对于情况三,取nums[1] 和 nums[3]就是最大的。
而情况二 和 情况三 都包含了情况一了,所以只考虑情况二和情况三就可以了。
分析到这里,本题其实比较简单了。
class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int len = nums.length;
if (len == 1)
return nums[0];
if(len ==2)
return Math.max(nums[0],nums[1]);
return Math.max(robAction(nums, 0, len - 2), robAction(nums, 1, len-1));
}
int robAction(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;
// 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];
}
}
第一种方法可以省点内存。
边栏推荐
- II. D3.js draw a simple figure -- circle
- Jeecg request URL signature
- Download address collection of various versions of devaexpress
- The difference between typescript let and VaR
- PHP install composer
- Use of framework
- Split small interface
- 2. E-commerce tool cefsharp autojs MySQL Alibaba cloud react C RPA automated script, open source log
- JS monitors empty objects and empty references
- Thoughts on project development
猜你喜欢
随机推荐
The embodiment of generics in inheritance and wildcards
在 4EVERLAND 上存储 WordPress 媒体内容,完成去中心化存储
Basic knowledge about SQL database
Arduino 软串口通信 的几点体会
C WinForm framework
JS monitors empty objects and empty references
Download address collection of various versions of devaexpress
Operation and maintenance technical support personnel have hardware maintenance experience in Hong Kong
Le Seigneur des anneaux: l'anneau du pouvoir
PHP install the spool extension
Distributed transactions
Advanced API (local simulation download file)
Deep learning parameter initialization (I) Xavier initialization with code
4279. 笛卡尔树
[solved] sqlexception: invalid value for getint() - 'Tian Peng‘
Shim and Polyfill in [concept collection]
JS date comparison
Homology policy / cross domain and cross domain solutions /web security attacks CSRF and XSS
docket
Advanced API (batch image Download & socket dialog)