当前位置:网站首页>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;
}
}边栏推荐
猜你喜欢

最新阿里P7技术体系,妈妈再也不用担心我找工作了

Personal notes of graphics (3)

Horizontal and vertical centering method and compatibility

The difference and working principle between compiler and interpreter

time标准库
正在准备面试,分享面经

Spark Tuning (III): persistence reduces secondary queries

Introduction and use of gateway

掌握这套精编Android高级面试题解析,oppoAndroid面试题

【医学分割】attention-unet
随机推荐
Pisa-Proxy SQL 解析之 Lex & Yacc
Cesium (4): the reason why gltf model is very dark after loading
"The" "PIP" "entry cannot be recognized as the name of a cmdlet, function, script file, or runnable program."
os、sys、random标准库主要功能
The latest interview experience of Android manufacturers in 2022, Android view+handler+binder
在哪个期货公司开期货户最安全?
Opencv configuration 2019vs
两类更新丢失及解决办法
QT中自定义控件的创建到封装到工具栏过程(二):自定义控件封装到工具栏
As an Android Developer programmer, Android advanced interview
全网“追杀”钟薛高
Direct dry goods, 100% praise
Opportunity interview experience summary
time标准库
【PHP】PHP接口继承及接口多继承原理与实现方法
Introduction to ThinkPHP URL routing
How does laravel run composer dump autoload without emptying the classmap mapping relationship?
Laravel post shows an exception when submitting data
Find tags in prefab in unity editing mode
使用JSON.stringify()去实现深拷贝,要小心哦,可能有巨坑