当前位置:网站首页>LeetCode213. 打家劫舍II
LeetCode213. 打家劫舍II
2022-06-28 21:00:00 【Yuyy】
本文最后更新于 484 天前,其中的信息可能已经有所发展或是发生改变。
一、思路
相比打家取舍一,不能同时偷第一家和最后家。就是多了个选择,要不偷第一家,要不偷最后家。 动态规划问题就是要在题目中找出选择,得出状态。
二、问题
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,能够偷窃到的最高金额。
示例 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 = [0]
输出:0提示:
1 <= nums.length <= 1000 <= nums[i] <= 1000
Related Topics
- 动态规划
\n
- 475
- 0
三、代码
public int rob(int[] nums) {
if (nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
return Math.max(rangeRob(nums, 0, nums.length - 2)
, rangeRob(nums, 1, nums.length - 1));
}
public int rangeRob(int[] nums, int start, int end) {
int[][] arr = new int[nums.length][2];
arr[start][1] = nums[start];
arr[start][0] = 0;
for (int i = start + 1; i <= end; i++) {
arr[i][1] = Math.max(arr[i - 1][0] + nums[i], arr[i - 1][1]);
arr[i][0] = Math.max(arr[i - 1][0], arr[i - 1][1]);
}
return Math.max(arr[end][0], arr[end][1]);
}Post Views: 249
边栏推荐
- The comprehensive application of the setstack computer (uva12096) Purple Book p116stl
- 数据资产为王,如何解析企业数字化转型与数据资产管理的关系?
- LeetCode每日一题——324. 摆动排序 II
- Application of Andy s first dictionary (uva10815) Purple Book p112set
- Flask——总结
- resilience4j 重试源码分析以及重试指标采集
- How to add logs to debug anr problems
- 学习太极创客 — MQTT 第二章(八)ESP8266 MQTT 用户密码认证
- Characters and integers
- Leetcode 36. 有效的数独(可以,一次过)
猜你喜欢

Data standardization processing

Ref attribute, props configuration, mixin mixing, plug-in, scoped style

Learn Tai Chi maker mqtt Chapter 2 (VIII) esp8266 mqtt user password authentication

with torch. no_ Grad(): reason for using

如何使用 DataAnt 监控 Apache APISIX

基于 Apache APISIX 的自动化运维平台

什么是接口?什么是接口测试?

postman简介与安装步骤

方 差 分 析

RT thread thread synchronization and thread communication
随机推荐
Resilience4j retry source code analysis and retry index collection
GlobalSign的泛域名SSL证书
如何使用 DataAnt 监控 Apache APISIX
Ehcache configuration data, convenient for self checking
Globalsign's Pan domain SSL certificate
Bitbucket failed to pull the warehouse Using SSH
I almost ran away
ANR无响应介绍
阿里云 MSE 基于 Apache APISIX 的全链路灰度方案实践
LeetCode:合并两个有序链表_21
oracle delete误删除表数据后如何恢复
LeetCode116. 填充每个节点的下一个右侧节点指针
Embedded dynamic Arabic string conversion LCD display string [thanks for Jianguo ambition]
券商公司开户哪个最靠谱最安全呢
[learning notes] Introduction to principal component analysis
How to add logs to debug anr problems
Leetcode daily question - 324 Swing sort II
我也差点“跑路”
Can you make money by speculating in stocks? It's safe to open an account
3. integrate listener