当前位置:网站首页>LeetCode 213. 打家劫舍 II 每日一题
LeetCode 213. 打家劫舍 II 每日一题
2022-07-07 15:32:00 【@小红花】
问题描述
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,今晚能够偷窃到的最高金额。
示例 1:
输入:nums = [2,3,2]
输出:3
解释:你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。
示例 2:输入:nums = [1,2,3,1]
输出:4
解释:你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。
偷窃到的最高金额 = 1 + 3 = 4 。
示例 3:输入:nums = [1,2,3]
输出:3
提示:
1 <= nums.length <= 100
0 <= nums[i] <= 1000来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/house-robber-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java
class Solution {
public int rob(int[] nums) {
int n = nums.length;
if(n == 1) return nums[0];
if(n == 2) return Math.max(nums[0],nums[1]);
return Math.max(getBenefit(nums,0,n - 2),getBenefit(nums,1,n - 1));
}
public int getBenefit(int[] nums,int left,int right){
int first = nums[left];
int second = Math.max(nums[left],nums[left + 1]);
for(int i = left + 2;i <= right;i++){
int temp = second;
second = Math.max(second,nums[i] + first);
first = temp;
}
return second;
}
}
边栏推荐
- ATM system
- The latest interview experience of Android manufacturers in 2022, Android view+handler+binder
- 字节跳动Android金三银四解析,android面试题app
- Sort out several important Android knowledge and advanced Android development interview questions
- typescript ts基础知识之tsconfig.json配置选项
- How can laravel get the public path
- 模拟Servlet的本质
- 【DesignMode】外观模式 (facade patterns)
- DNS 系列(一):为什么更新了 DNS 记录不生效?
- Laravel5.1 Routing - routing packets
猜你喜欢
随机推荐
3000 words speak through HTTP cache
Common training data set formats for target tracking
Geoserver2.18 series (5): connect to SQLSERVER database
[vulnhub range] thales:1
"The" "PIP" "entry cannot be recognized as the name of a cmdlet, function, script file, or runnable program."
Record the migration process of a project
全网“追杀”钟薛高
ATM系统
Opportunity interview experience summary
《产品经理必读:五种经典的创新思维模型》的读后感
两类更新丢失及解决办法
最新Android高级面试题汇总,Android面试题及答案
QT中自定义控件的创建到封装到工具栏过程(二):自定义控件封装到工具栏
Find tags in prefab in unity editing mode
[C language] question set of X
Asyncio concept and usage
使用JSON.stringify()去实现深拷贝,要小心哦,可能有巨坑
掌握这个提升路径,面试资料分享
预售17.9万,恒驰5能不能火?产品力在线,就看怎么卖
Build an all in one application development platform, light flow, and establish a code free industry benchmark