当前位置:网站首页>[dynamic planning -- the best period for buying and selling stocks Series 2]
[dynamic planning -- the best period for buying and selling stocks Series 2]
2022-07-28 06:40:00 【Step by step b】
Force button topic link
Given an array of integers , Among them the first i Elements represent the i Day's share price .
Design an algorithm to calculate the maximum profit . Under the following constraints , You can do as many deals as you can ( Buy and sell a stock many times ):
You can't participate in multiple transactions at the same time ( You have to sell the stock before you buy it again ).
After sale of shares , You can't buy shares the next day ( That is, the freezing period is 1 God ).
example
Input :[1,2,3,0,2]
Output :3
explain : The corresponding transaction status is : [ purchase , sell , Freezing period , purchase , sell ]
Dynamic programming 5 Step curve
- determine dp The meaning of arrays and subscripts
dp[i][j], The first i Day status is j, The maximum cash left is dp[i][j].
The state of this question is relative to A series of It's a lot more complicated . Specifically, it is divided into the following four states :
- State one : Buy stock status ( Buy stocks today , Or you bought stocks before and didn't operate )
Status of selling shares , There are two states of selling stocks
- State two : Sold the stock two days ago , Passed the freezing period , Never operated , Keep selling stocks today
- State three : I sold shares today
- State four : Today is in a frozen state , But the frozen state is unsustainable , Only one day !
Notice every state here , For example, state one , The status of buying stocks does not mean that you have bought stocks today , It means to keep the status of buying stocks, that is : It may have been bought a few days ago , I haven't operated since , So keep buying stocks .
j The status of is :
0: State one ;1: State two ;2: State three ;3: State four
Determine the recurrence formula
Reach the status of buying stocks ( State one ) namely :dp[i][0], There are two specific operations :
Operation 1 : The day before, I was holding stocks ( State one ),dp[i][0] = dp[i - 1][0]
Operation two : I bought it today , There are two situations
The day before was frozen ( State four ),dp[i - 1][3] - prices[i]
The previous day was to keep selling stocks ( State two ),dp[i - 1][1] - prices[i]
So operation two takes the maximum value , namely :max(dp[i - 1][3], dp[i - 1][1]) - prices[i]
that dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][3], dp[i - 1][1]) - prices[i]);
To keep selling stocks ( State two ) namely :dp[i][1], There are two specific operations :
Operation 1 : The day before was state two
Operation two : The day before was frozen ( State four )
dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]);
Reach the state of selling stocks today ( State three ), namely :dp[i][2] , There's only one operation :
Operation 1 : Yesterday must have been a stock buying state ( State one ), Sell today
namely :dp[i][2] = dp[i - 1][0] + prices[i];
Reach the freezing state ( State four ), namely :dp[i][3], There's only one operation :
Operation 1 : I sold the stock yesterday ( State three )
dp[i][3] = dp[i - 1][2];
To sum up, we get a recursive formula :
dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][3], dp[i - 1][1]) - prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]);
dp[i][2] = dp[i - 1][0] + prices[i];
dp[i][3] = dp[i - 1][2];
dp How to initialize an array
Here we mainly discuss the second 0 How to initialize .
If you are holding shares ( State one ) that :dp[0][0] = -prices[0], The cash left over from buying stocks is negative .
Keep selling stocks ( State two ), The first 0 I haven't sold for days dp[0][1] Initialize to 0 Just go .
I sold shares today ( State three ), Again dp[0][2] Initialize to 0, Because the least benefit is 0, It will never be negative .
Empathy dp[0][3] Also initially 0.
Determine the traversal order
As can be seen from the recursive formula ,dp[i] Depend on dp[i-1], So it's going from front to back .
Give an example to deduce dp Array
With [1,2,3,0,2] For example ,dp The array is as follows :
The final result is to take State two , State three , And the maximum value of state four .
The code is as follows :
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution{
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
if (n == 0) return 0;
vector<vector<int>> dp(n,vector<int>(4,0));
dp[0][0] = -prices[0];
for (int i = 1; i < n; i++) {
dp[i][0] = max({
dp[i-1][0],dp[i-1][1]-prices[i],dp[i-1][3]-prices[i]});
// Buy stock status
dp[i][1] = max(dp[i-1][1],dp[i-1][3]);
// Sold shares two days ago , Passed the freezing period , There has been no operation , Keep selling stocks today
dp[i][2] = dp[i-1][0] + prices[i];
// I sold shares today
dp[i][3] = dp[i-1][2];
// Today is the freezing period , But the frozen state is unsustainable , Only one day
}
return max({
dp[n-1][3],dp[n-1][2],dp[n-1][1]});
}
};
int main() {
Solution Q;
int n;
cin>>n;
vector<int> price(n);
for (int i = 0; i < n; i++) {
cin>>price[i];
}
cout<<Q.maxProfit(price);
}
边栏推荐
- Hugging face's problem record I
- valgrind工具
- 动态规划--多步爬楼梯(爬楼梯进阶版)
- 气传导蓝牙耳机哪个好、气传导蓝牙耳机排行榜
- OJ 1507 deletion problem
- 2022-07-19 Damon database connection instance, execution script, system command
- 2022-05-15 based on JWT token
- [basic knowledge of binary tree]
- 【无标题】
- What is hash? (development of Quantitative Trading Robot System)
猜你喜欢

Leetcode 刷题日记 剑指 Offer II 048. 序列化与反序列化二叉树

自定义组件--样式

SSAO By Computer Shader(二)

MFC uses the console to print program information

七夕送什么礼物最实用?送人绝对不会出错的礼物值得买

小程序自定义组件-数据,方法和属性
![[PTA----树的遍历]](/img/d8/260317b30d624f8e518f8758706ab9.png)
[PTA----树的遍历]

Solve the problem that the memory occupation is higher than that of the application process
![OpenGL development environment configuration [vs2017] + frequently asked questions](/img/29/cefa8601310caf56ae9605cbf7fbbf.png)
OpenGL development environment configuration [vs2017] + frequently asked questions

图形管线基础(一)
随机推荐
What's a good gift for your girlfriend on the Chinese Valentine's day in 2022? Practical and beautiful gift recommendation
数组解法秘籍
【动态规划--买卖股票的最佳时期系列】
scrapy 命令
Leetcode 刷题日记 剑指 Offer II 050. 向下的路径节点之和
【二叉树基础知识】
Getting started with hugging face
Code neatness (2)
[PTA--利用队列解决猴子选大王问题】
Current learning progress
OJ 1505 保险丝
Treasure plan TPC system development DAPP construction
[C note] data type and storage
[队列,栈的简单应用----包装机]
图形管线基础(一)
SSAO By Computer Shader(二)
从普通查询商品到高并发查询商品的优化思路
Icc2 (IV) routing and postroute optimization
OJ 1253 点菜问题
小程序创建组件