当前位置:网站首页>Dynamic programming stock problem comparison
Dynamic programming stock problem comparison
2022-07-04 17:31:00 【Folded cookies】
Core or state transition , It's easy to figure out what each state is
If you don't know the transfer process, you can make a watch
From here dp[i][j],i from 1 At first, it's because I habitually want to avoid i-1 Lead to cross-border
1
121. The best time to buy and sell stocks
Given an array prices , It's the first i Elements prices[i] Represents the number of shares in a given stock i Sky price .
You can only choose One day Buy this stock , And choose A different day in the future Sell the stock . Design an algorithm to calculate the maximum profit you can get .
Return the maximum profit you can make from the deal . If you can't make any profit , return 0 .
The finger of the sword Offer 63. The biggest profit of stocks
What is the maximum profit that can be obtained by buying and selling this stock at one time ?
analysis :
These two questions are the same , You can only buy and sell once
The following two methods just think from different angles :
1.dp[i][0] and dp[i][1] Respectively represents no shares ( Maybe I didn't buy , It may be sold )、 There are stocks ( Only once , Therefore, the last value cannot be superimposed ) Two kinds of state
%2 It's a way to save space , Can not add
2.
dp[i][0] Never bought it
dp[i][1] I bought it once , And not sold
dp[i][2] I bought it once , And sell
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len=prices.size();
vector<vector<int>>dp(2,vector<int>(2,0));
int ans=0;
dp[1][0]=0;
dp[1][1]=-prices[0];
for(int i=2;i<=len;i++){
dp[i%2][0]=max(dp[(i-1)%2][0],dp[(i-1)%2][1]+prices[i-1]);
dp[i%2][1]=max(dp[(i-1)%2][1],-prices[i-1]);
}
return dp[len%2][0];
}
};
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len=prices.size();
if(len==0)return 0;
vector<vector<int>>dp(len+1,vector<int>(3,0));
dp[1][1]=-prices[0];
for(int i=2;i<=len;i++){
dp[i][0]=dp[i-1][0];
dp[i][1]=max(dp[i-1][0]-prices[i-1],dp[i-1][1]);
dp[i][2]=max(dp[i-1][1]+prices[i-1],dp[i-1][2]);
}
return dp[len][2];
}
};
2
122. The best time to buy and sell stocks II
Give you an array of integers prices , among prices[i] Represents a stock i Sky price .
Every day , You can decide whether to buy and / Or sell shares . You at any time most Can only hold A wave of Stocks . You can also buy... First , And then in On the same day sell .
return What you can get Maximum profits .
analysis :
and 1 comparison , You can buy and sell many times , It means that buying can superimpose the last state
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len=prices.size();
vector<vector<int>>dp(len+1,vector<int>(2,0));
dp[1][1]=-prices[0];
dp[1][0]=0;
for(int i=2;i<=len;i++){
dp[i][0]=max(dp[i-1][0],dp[i-1][1]+prices[i-1]);
dp[i][1]=max(dp[i-1][1],dp[i-1][0]-prices[i-1]);
}
return dp[len][0];
}
};
3
123. The best time to buy and sell stocks III
Given an array , It's the first i An element is a given stock in the i Sky price .
Design an algorithm to calculate the maximum profit you can get . You can do at most Two pens transaction .
Be careful : You can't participate in multiple transactions at the same time ( You have to sell the stock before you buy it again ).
analysis :
and 2 comparison , Limit the number of purchases , You can only buy twice
Just use 5 Status flags
dp[i][0] Never bought it
dp[i][1] I bought it once , And hold
dp[i][2] I bought it once , And sold
dp[i][3] I bought it twice , And hold
dp[i][4] I bought it twice , And sold
Note initialization , You can buy and sell and buy all day
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len=prices.size();
vector<vector<int>>dp(len+1,vector<int>(5,0));
dp[1][1]=-prices[0];
// Note that you can buy and sell twice a day
dp[1][3]=-prices[0];
for(int i=2;i<=len;i++){
dp[i][0]=dp[i-1][0];
dp[i][1]=max(dp[i-1][0]-prices[i-1],dp[i-1][1]);
dp[i][2]=max(dp[i-1][1]+prices[i-1],dp[i-1][2]);
dp[i][3]=max(dp[i-1][2]-prices[i-1],dp[i-1][3]);
dp[i][4]=max(dp[i-1][3]+prices[i-1],dp[i-1][4]);
}
return dp[len][4];
}
};
4
188. The best time to buy and sell stocks IV
Given an array of integers prices , It's the first i Elements prices[i] Is a given stock in the i Sky price .
Design an algorithm to calculate the maximum profit you can get . You can do at most k transaction .
Be careful : You can't participate in multiple transactions at the same time ( You have to sell the stock before you buy it again )
analysis :
and 3 comparison , Buy twice and change k Time
Just use 2k+1 Status flags
dp[i][0] Never bought it
dp[2i+1][1] I bought it once , And hold
dp[ik+2][2] I bought it once , And sold
Then the cycle is over
Note initialization , You can buy, sell, buy and …
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int len=prices.size();
if(len==0)return 0;
vector<vector<int>>dp(len+1,vector<int>(2*k+1,0));
for(int i=0;i<k;i++){
dp[1][2*i+1]=-prices[0];
}
for(int i=2;i<=len;i++){
dp[i][0]=dp[i-1][0];
for(int j=0;j<k;j++){
dp[i][2*j+1]=max(dp[i-1][2*j]-prices[i-1],dp[i-1][2*j+1]);
dp[i][2*j+2]=max(dp[i-1][2*j+1]+prices[i-1],dp[i-1][2*j+2]);
}
}
return dp[len][2*k];
}
};
5
714. The best time to buy and sell stocks includes handling fees
Given an array of integers prices, among prices[i] It means the first one i Day's share price ; Integers fee Represents the handling fee for trading shares .
You can close the deal indefinitely , But you have to pay a handling fee for every transaction . If you have bought a stock , You can't buy any more stock until you sell it .
Return the maximum profit .
Be careful : A deal here refers to the whole process of buying, holding and selling stocks , You only need to pay a handling fee for each transaction .
analysis :
Follow 2 comparison , At the time of sale -fee Just go
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int len=prices.size();
vector<vector<int>>dp(len+1,vector<int>(2,0));
dp[1][1]=-prices[0];
for(int i=2;i<=len;i++){
dp[i][0]=max(dp[i-1][0],dp[i-1][1]+prices[i-1]-fee);
dp[i][1]=max(dp[i-1][1],dp[i-1][0]-prices[i-1]);
}
return dp[len][0];
}
};
边栏推荐
- R语言plotly可视化:plotly可视化多分类变量小提琴图(multiple variable violin plot in R with plotly)
- Master the use of auto analyze in data warehouse
- [acwing] 58 weeks 4489 Longest subsequence
- Redis 的内存淘汰策略和过期删除策略的区别
- leetcode刷题目录总结
- R语言plotly可视化:plotly可视化互相重叠的直方图(historgram)、并在直方图的顶部边缘使用geom_rug函数添加边缘轴须图Marginal rug plots
- MVC模式和三层架构
- 缓存穿透、缓存击穿、缓存雪崩分别是什么
- CANN算子:利用迭代器高效实现Tensor数据切割分块处理
- 7 RSA密码体制
猜你喜欢

NFT liquidity market security issues occur frequently - Analysis of the black incident of NFT trading platform quixotic

聊聊异步编程的 7 种实现方式

解读数据安全治理能力评估框架2.0,第四批DSG评估征集中

如何实现一个延时队列 ?

新的职业已经出现,怎么能够停滞不前 ,人社部公布建筑新职业

La 18e Conférence internationale de l'IET sur le transport d'électricité en courant alternatif et en courant continu (acdc2022) s'est tenue avec succès en ligne.

detectron2安装方法

矿产行业商业供应链协同系统解决方案:构建数智化供应链平台,保障矿产资源安全供应

VSCode修改缩进不成功,一保存就缩进四个空格

Analysis of abnormal frequency of minor GC in container environment
随机推荐
leetcode:421. The maximum XOR value of two numbers in the array
电子元器件B2B商城系统开发:赋能企业构建进销存标准化流程实例
Solution of dealer collaboration system in building materials industry: empowering enterprises to build core competitiveness
To sort out messy header files, I use include what you use
leetcode:421. 数组中两个数的最大异或值
Oppo Xiaobu launched Obert, a large pre training model, and promoted to the top of kgclue
完美融入 Win11 风格,微软全新 OneDrive 客户端抢先看
[template] [Luogu p4630] duathlon Triathlon (round square tree)
将Opencv绘制图片显示在MFC Picture Control控件上
聊聊异步编程的 7 种实现方式
wuzhicms代码审计
什么是低代码开发?
What are cache penetration, cache breakdown, and cache avalanche
中信证券网上开户安全吗 开户收费吗
tx.origin安全问题总结
VB cannot access database stocks
长城证券开户安全吗 证券账户怎么开通
Congratulations to Mr. Zhang Pengfei, chief data scientist of artefact, for winning the campaign Asia tech MVP 2022
The test experience "tortured" by the PMP test is worth your review
World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection