当前位置:网站首页>LeetCode 122:买卖股票的最佳时机 II
LeetCode 122:买卖股票的最佳时机 II
2022-07-26 21:38:00 【斯沃福德】
题目:
思路:动态规划
上一题最大交易次数K=1,而此题不限制K,即K为无穷,
则两个状态转移方程:
- 今天没有:昨天也没有 + 昨天有、卖了
- 今天持有:昨天也持有 + 昨天没有、买了

由于数组中的 k 已经不会改变了,也就是说不需要记录 k 这个状态了:
Java实现:
注意:
代码部分和上一题121几乎一样,
区别在于 求今天有时, 昨天没有、今天买了是 dp[i-1][0]-prices[i] ,符合逻辑;
而121题是 -prices[i] !!!
class Solution {
public int maxProfit(int[] prices) {
int n=prices.length;
int[][] dp=new int[n][2];
// base case
dp[0][0]=0;
dp[0][1]=-prices[0];
// 遍历状态
for(int i=1;i<n;i++){
//今天没有: 昨天没有 + 昨天有、卖了
dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]+prices[i] );
//今天有:昨天有 + 昨天没有、买了
dp[i][1]=Math.max(dp[i-1][1],dp[i-1][0]-prices[i] );
}
return dp[n-1][0];
}
}
边栏推荐
- MySQL recommendation
- matlab 短时自相关实现
- Xshell7 personal free download, use
- Add resource files for the project and pictures for buttons in QT
- [waiting and wakeup of QT multithreaded threads]
- MOS 管示意图
- What you need to know about mobile video compatibility
- Qt中为工程添加资源文件、给按钮添加图片
- Open source | arex Ctrip traffic playback practice without code intrusion
- 博客园美化技巧汇总
猜你喜欢

mysql推荐书

Unity installation failed: operation not allowed, MKDIR

Unity operates on Explorer, opens explorer, selects files, and filters files

Oppo self-developed large-scale knowledge map and its application in digital intelligence engineering

Nacos作为注册中心、配置中心入门使用篇-实现远程调用、动态获取配置文件、数据库配置信息

Development to testing: a six-year road to automation from scratch

小白学习MySQL - Derived Table

2018 arXiv preprint | MolGAN: An implicit generative model for small molecular graphs

Chapter 15 MySQL user management

Want the clouds in the picture to float? Video editing services can be achieved in three steps with one click
随机推荐
d和c的符区别
[RequireComponent(typeof(....))]
iptables防止nmap扫描以及binlog实现增量备份
07 DF command
Iptables prevents nmap scanning and enables incremental backup of binlog
easyui datagrid 获取多条选中的数据进行操作
寻找数字零售的发展新方向,才是保证数字零售可以进入到全新发展阶段的关键
Finding a new direction for the development of digital retail is the key to ensure that digital retail can enter a new stage of development
Matlab draw short-term energy diagram
Excel VBA quick start (XII. Common usage of like comparison)
Protobuf之proto基础语法
国信证券手机开户收费吗?开户安全吗?
【地平线旭日X3派试用体验】+开箱帖
蔚来杯2022牛客暑期多校训练营1
matlab 画短时平均幅度谱
Oppo self-developed large-scale knowledge map and its application in digital intelligence engineering
Understanding and practice of the trend of Bank of London foreign exchange
Afnetworking understand
Let Xiaobai thoroughly understand performance tuning
leetcode:857. 雇佣 K 名工人的最低成本【分块思考 + 由简单入手】