当前位置:网站首页>188. 买卖股票的最佳时机 IV
188. 买卖股票的最佳时机 IV
2022-06-24 19:19:00 【anieoo】
原题链接:188. 买卖股票的最佳时机 IV
solution:
和买卖股票系列3是一样的方法,只不过交易次数为k次。
const int INF = 0x3f3f3f3f;
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if(n == 0) return 0;
vector<vector<vector<int>>> dp(n + 1, vector<vector<int>> (2, vector<int> (k + 1)));
dp[1][1][0] = -prices[0];
dp[1][0][0] = 0;
//第一天不可能完成交易
for(int i = 1;i <= k;i++)
dp[1][0][i] = -INF;
// 第一天不可能已经卖出
for(int i = 1;i <= k;i++)
dp[1][1][i] = -INF;
for(int i = 2;i <= n;i++){
for(int j = 1;j <= k;j++){
dp[i][0][j] = max(dp[i - 1][0][j],dp[i - 1][1][j - 1] + prices[i - 1]);
}
dp[i][1][0] = max(dp[i - 1][1][0], dp[i - 1][0][0] - prices[i - 1]);
for(int j = 1;j <= k;j++) {
dp[i][1][j] = max(dp[i - 1][1][j], dp[i - 1][0][j] - prices[i - 1]);
}
}
int res = 0;
for(int i = 1;i <= k;i++){
res = max(res,dp[n][0][i]);
}
return res;
}
};
边栏推荐
- 海泰前沿技术|隐私计算技术在医疗数据保护中的应用
- Reflection - class object function - get method (case)
- VIM usage
- After idea installs these plug-ins, the code can be written to heaven. My little sister also has to arrange it
- Dijkstra seeking secondary short circuit (easy to understand)
- Pytest test framework II
- Common self realization functions in C language development
- Leetcode(146)——LRU 缓存
- Adding subscribers to a list using mailchimp's API V3
- 网络安全审查办公室对知网启动网络安全审查
猜你喜欢

Responsibility chain mode -- through interview

How to apply agile development ideas to other work

After idea installs these plug-ins, the code can be written to heaven. My little sister also has to arrange it

Php-pdo parameter binding problem

yeb_ Back first day

JMeter basic learning records

传统的IO存在什么问题?为什么引入零拷贝的?

Pod lifecycle in kubernetes

After a few years in the testing industry, do you still know a little?

虚拟化是什么意思?包含哪些技术?与私有云有什么区别?
随机推荐
go_ keyword
OSI notes sorting
Use the transparent [x] cross button image in the dialog
[普通物理] 光栅衍射
Leetcode (135) - distribute candy
It was Tencent who jumped out of the job with 26k. It really wiped my ass with sandpaper. It gave me a hand
After screwing the screws in the factory for two years, I earned more than 10000 yuan a month by "testing" and counterattacked
Combination mode -- stock speculation has been cut into leeks? Come and try this investment strategy!
Background of master data construction
Smooth live broadcast | analysis of key technologies for live broadcast pain points
Basic database syntax learning
Pyaudio audio recording
Vant component used in wechat applet
Rip/ospf protocol notes sorting
Address mapping of virtual memory paging mechanism
Leetcode(146)——LRU 缓存
Berkeley, MIT, Cambridge, deepmind and other industry leaders' online lectures: towards safe, reliable and controllable AI
How to apply agile development ideas to other work
JMeter installation plug-in, adding [email protected] -Perfmon metric collector listener steps
刚购买了一个MYSQL数据库,提示已有实例,控制台登录实例要提供数据库账号,我如何知道数据库账号。