当前位置:网站首页>198. 打家劫舍
198. 打家劫舍
2022-06-24 08:03:00 【zzu菜】
198. 打家劫舍
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
示例 1:
输入:[1,2,3,1]
输出:4
解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
偷窃到的最高金额 = 1 + 3 = 4 。
示例 2:
输入:[2,7,9,3,1]
输出:12
解释:偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
偷窃到的最高金额 = 2 + 9 + 1 = 12 。
思考
定义dp数组及其下标的含义
dp[i]:表示前i天可以偷取到的最大金额为dp[i]
初始化dp数组
初始化dp[0] 和 dp[1]
状态转移方程
dp[i] = Max{dp[i-1], dp[i-2]+nums[i] }
class Solution {
public int rob(int[] nums) {
if(nums.length==1) return nums[0];
//step 1 创建dp数组
int[] dp=new int[nums.length];
// step 2 初始化dp数组
dp[0] = nums[0];
if(nums[1]>nums[0])
dp[1] = nums[1];
else dp[1] = dp[0];
if(dp.length==2) return dp[1];
// step 3 完善dp数组
for (int i=2;i<dp.length;i++){
dp[i] = Math.max(dp[i-1],dp[i-2]+nums[i]);
}
return dp[dp.length-1];
}
}
边栏推荐
- [use picgo+ Tencent cloud object to store cos as a map bed]
- Common emoticons
- Tools
- 软件系统依赖关系分析
- 陆奇:我现在最看好这四大技术趋势
- Data middle office: overview of data governance
- linux(centos7.9)安装部署mysql-cluster 7.6
- 牛客网 字符串变形
- Qingcloud based R & D cloud solution for geographic information enterprises
- 【ES6闯关】Promise堪比原生的自定义封装(万字)
猜你喜欢
Depens:*** but it is not going to be installed

Spark - the number of leftouterjoin results is inconsistent with that of the left table

Opencv daily function structure analysis and shape descriptor (7) finding polygon (contour) / rotating rectangle intersection

NETRCA: AN EFFECTIVE NETWORK FAULT CAUSE LOCALIZATION之论文阅读

Mba-day25 best value problem - application problem

Kaformer personal notes

Rpiplay implementation of raspberry pie airplay projector

Redis实现全局唯一ID

关于 GIN 的路由树

From the Huawei weautomate digital robot forum, we can see the "new wisdom of government affairs" in the field of government and enterprises
随机推荐
Depens:*** but it is not going to be installed
解决:jmeter5.5在win11下界面上的字特别小
Rpiplay implementation of raspberry pie airplay projector
Data middle office: the data middle office practice scheme of Minsheng Bank
【Redis实现秒杀业务①】秒杀流程概述|基本业务实现
[redis realize Secondary killing Business ①] Overview of Secondary killing Process | Basic Business Realization
pm2 部署 nuxt3.js 项目
Opencv maximum filtering (not limited to images)
Some common pitfalls in getting started with jupyter:
【ES6闯关】Promise堪比原生的自定义封装(万字)
216. combined summation III enumeration method
十二、所有功能实现效果演示
学习太极创客 — ESP8226 (十三)OTA
每周推荐短视频:计算的终极形态是“元宇宙”?
【gdb调试工具】| 如何在多线程、多进程以及正在运行的程序下调试
零基础自学SQL课程 | HAVING子句
The printed object is [object object]. Solution
4275. Dijkstra序列
MYCAT read / write separation and MySQL master-slave synchronization
Solution: the word of jmeter5.5 on the win11 lower interface is very small