当前位置:网站首页>LeetCode-198-打家劫舍
LeetCode-198-打家劫舍
2022-07-25 14:35:00 【z754916067】
题目

思路
- 感觉是动态规划,要不从0开始抢 要不从1开始抢
- dp[i]代表必须抢劫第i户时的最高金额,但是其有可能抢i-2户和抢i-3户,因为无法抢劫i-1户,且如果抢劫i-4户的话那么也可以抢i-2户,所以只需要考虑抢i-2和i-3j即可
代码
public int rob(int[] nums) {
if(nums.length<2) return nums[0];
//感觉是动态规划
int[] dp = new int[nums.length];
int ans = Integer.MIN_VALUE;
//要不从0开始抢 要不从1开始抢
dp[0]=nums[0];
dp[1]=nums[1];
ans = Math.max(dp[0],dp[1]);
//dp[i]代表必须抢劫第i户时的最高金额
//但是其有可能不抢i-2户而抢i-3户
for(int i=2;i<nums.length;i++){
if(i-3>=0) dp[i]=Math.max(nums[i]+dp[i-2],nums[i]+dp[i-3]);
else dp[i]=nums[i]+dp[i-2];
ans = Math.max(ans,dp[i]);
}
return ans;
}
边栏推荐
- Teach you how to apply for SSL certificate
- Summary of some problems about left value and right value [easy to understand]
- Alibaba cloud installs mysql5.7
- How to design a high concurrency system?
- Deep understanding of pytorch distributed parallel processing tool DDP -- starting from bugs in engineering practice
- Software testing -- 1. Outline of software testing knowledge
- Products on Apple's official website can save 600 yuan by buying iPhone 13 Pro max at a discount
- Idea regular expression replacement (idea regular search)
- thymeleaf设置disabled
- Two Sum
猜你喜欢

Initial flask and simple application

The concept and operation rules of calculus of variations

PS making and loading GIF pictures tutorial

安防市场进入万亿时代,安防B2B网上商城平台精准对接深化企业发展路径

Idea error failed to determine a suitable driver class

sudo rosdep init Error ROS安装问题解决方案

Why do China Construction and China Railway need this certificate? What is the reason?

PHP website design ideas

Wechat official account official environment online deployment, third-party public platform access

GameFramework制作游戏(一)
随机推荐
关于左值和右值的一些问题总结[通俗易懂]
【cartographer_ros】八: 官方Demo参数配置和效果
filters获取data中的数据;filters使用data中的数据
国联证券买股票开户安全吗?
各种平台dpkg包下载地址(包括arm64)
Filters get the data in data; Filters use data in data
Opencv video tracking "suggestions collection"
Gameframework making games (II) making UI interface
Gameframework making games (I)
PHP website design ideas
PS making and loading GIF pictures tutorial
~5 new solution of CCF 2021-12-2 sequence query
Realsense-Ros安装配置介绍与问题解决
Educational codeforces round 132 (rated for Div. 2) C, d+ac automata
Quickly set up dobbo demo
H5页面input输入框弹起数字键盘,需要支持小数点
Teach you how to apply for SSL certificate
QObject source code analysis -d pointer and Q pointer
【MySQL必知必会】触发器 | 权限管理
GameFramework制作游戏(一)