当前位置:网站首页>198. Looting - Dynamic Planning
198. Looting - Dynamic Planning
2022-04-23 17:33:00 【hequnwang10】
One 、 Title Description
You are a professional thief , Plan to steal houses along the street . There is a certain amount of cash in every room , The only restriction on your theft is that adjacent houses are equipped with interconnected anti-theft systems , If two adjacent houses are broken into by thieves on the same night , The system will automatically alarm .
Given an array of non negative integers representing the storage amount of each house , Count you Without triggering the alarm , The maximum amount that can be stolen overnight .
Example 1:
Input :[1,2,3,1]
Output :4
explain : Steal 1 House No ( amount of money = 1) , And then steal 3 House No ( amount of money = 3).
Maximum amount stolen = 1 + 3 = 4 .
Example 2:
Input :[2,7,9,3,1]
Output :12
explain : Steal 1 House No ( amount of money = 2), Steal 3 House No ( amount of money = 9), Then steal 5 House No ( amount of money = 1).
Maximum amount stolen = 2 + 9 + 1 = 12 .
Two 、 Problem solving
Dynamic programming
dp[i] Indicates that the subscript is i The maximum value that can be stolen when it is a subscript .
dp[i]=max(dp[i−2]+nums[i],dp[i−1])
class Solution {
public int rob(int[] nums) {
// The idea of solving problems is relatively simple According to the formula
//dp[i]=max(dp[i−2]+nums[i],dp[i−1])
int length = nums.length;
if(length == 0 || nums == null){
return 0;
}
if(length == 1){
return nums[0];
}
int[] dp = new int[length+1];
dp[1] = nums[0];
for(int i = 2;i<=length;i++){
dp[i] = Math.max(dp[i-2]+nums[i-1],dp[i-1]);
}
return dp[length];
}
}
版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231732009140.html
边栏推荐
猜你喜欢

常用SQL语句总结

Exercise: even sum, threshold segmentation and difference (two basic questions of list object)

为什么有些人说单片机简单,我学起来这么吃力?
MySQL installation

QT modification UI does not take effect

394. 字符串解码-辅助栈

92. 反转链表 II-字节跳动高频题

Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory

Double pointer advanced -- leetcode title -- container with the most water

Signalr can actively send data from the server to the client
随机推荐
Understanding of RPC core concepts
Understanding and small examples of unity3d object pool
386. 字典序排数(中等)-迭代-全排列
Shell-cut命令的使用
Double pointer advanced -- leetcode title -- container with the most water
JVM class loading mechanism
[ES6] promise related (event loop, macro / micro task, promise, await / await)
Promise (III)
QT modification UI does not take effect
2.Electron之HelloWorld
线性代数感悟之2
Node template engine (EJS, art template)
Use of shell sed command
Collection of common SQL statements
ASP. Net core JWT certification
Manually implement call, apply and bind functions
31. 下一个排列
ASP. Net core configuration options (Part 1)
快时钟同步慢时钟域下的异步控制信号slow clk to fast clk
Use of Shell sort command