当前位置:网站首页>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;
}
}边栏推荐
- three. JS create cool snow effect
- 水平垂直居中 方法 和兼容
- Opencv configuration 2019vs
- Have fun | latest progress of "spacecraft program" activities
- ORACLE进阶(六)ORACLE expdp/impdp详解
- 直接上干货,100%好评
- Sqlserver2014+: create indexes while creating tables
- Master this promotion path and share interview materials
- 【PHP】PHP接口继承及接口多继承原理与实现方法
- 如何选择合适的自动化测试工具?
猜你喜欢

AutoLISP series (2): function function 2

《产品经理必读:五种经典的创新思维模型》的读后感
正在准备面试,分享面经

node:504报错

HAVE FUN | “飞船计划”活动最新进展

The team of East China Normal University proposed the systematic molecular implementation of convolutional neural network with DNA regulation circuit

Personal notes of graphics (2)

整理几个重要的Android知识,高级Android开发面试题

Record the migration process of a project

Master this promotion path and share interview materials
随机推荐
C语言进阶——函数指针
水平垂直居中 方法 和兼容
Introduction to ThinkPHP URL routing
Balanced binary tree (AVL)
[summary of knowledge] summary of notes on using SVN in PHP
爬虫(17) - 面试(2) | 爬虫面试题库
Find tags in prefab in unity editing mode
pycharm 终端部启用虚拟环境
ORACLE进阶(六)ORACLE expdp/impdp详解
【图像传感器】相关双采样CDS
LeetCode-SQL第一天
AutoLISP series (1): function function 1
全网“追杀”钟薛高
Personal notes of graphics (2)
记录Servlet学习时的一次乱码
偶然升职的内心独白
《产品经理必读:五种经典的创新思维模型》的读后感
正在准备面试,分享面经
[PHP] PHP interface inheritance and interface multi inheritance principle and implementation method
值得一看,面试考点与面试技巧