当前位置:网站首页>Leetcode 0123. the best time to buy and sell stocks III: dynamic programming + simulation in constant space
Leetcode 0123. the best time to buy and sell stocks III: dynamic programming + simulation in constant space
2022-07-24 23:57:00 【Tisfy】
【LetMeFly】123. The best time to buy and sell stocks III: Dynamic programming in constant space + simulation
Force button topic link :https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-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 ).
Example 1:
Input :prices = [3,3,5,0,0,3,1,4] Output :6 explain : In the 4 God ( Stock price = 0) Buy when , In the 6 God ( Stock price = 3) Sell when , The exchange will make a profit = 3-0 = 3 . And then , In the 7 God ( Stock price = 1) Buy when , In the 8 God ( Stock price = 4) Sell when , The exchange will make a profit = 4-1 = 3 .
Example 2:
Input :prices = [1,2,3,4,5] Output :4 explain : In the 1 God ( Stock price = 1) Buy when , In the 5 God ( Stock price = 5) Sell when , The exchange will make a profit = 5-1 = 4 . Notice that you can't be in the 1 Day and day 2 Day after day buying stock , Then sell them . Because it's involved in multiple transactions at the same time , You have to sell the stock before you buy it again .
Example 3:
Input :prices = [7,6,4,3,1] Output :0 explain : In this case , No deal is done , So the biggest profit is 0.
Example 4:
Input :prices = [1] Output :0
Tips :
1 <= prices.length <= 1050 <= prices[i] <= 105
Method 1 : Dynamic programming in constant space
This question, frankly speaking, has at most 5 5 5 Status :
- There has been no transaction
- Made a purchase
- Made a deal
- Made a deal + One time purchase
- Two transactions
When there is no transaction , The profit is 0 0 0, Therefore, there is no need to pay special attention .
Use four variables b u y 1 , s e l l 1 , b u y 2 , s e l l 2 buy1, sell1, buy2, sell2 buy1,sell1,buy2,sell2 When the transaction reaches the remaining four states , The current maximum profit .( Here, try to match the variable name with Official explanation bring into correspondence with )
Next, we strictly abide by the meaning of the above four variables
Assign the initial values of the four variables to the maximum profit value after the first day :
- b u y 1 buy1 buy1: On the first day, I made a purchase . Then the current maximum profit is Negative first day share price Negative first day share price Negative first day share price ( It's the biggest profit , In fact, the first day of this state, there is no choice , There is only one profitable result )
- s e l l 1 sell1 sell1: On the first day, a deal was made . Then the buying and selling prices are the same , The current maximum profit is 0 0 0
- b u y 2 buy2 buy2: On the first day, a deal was made + One time purchase . That is to say, I bought it once on the first day and sold it immediately , Then I bought it again , total ( Maximum ) Profit for Negative first day share price Negative first day share price Negative first day share price
- s e l l 2 sell2 sell2: On the first day, there were two transactions . The total revenue is 0 0 0
int buy1 = -prices[0]
int sell1 = 0;
int buy2 = -prices[0]
int sell2 = 0;
Next , From 2 2 2 Day begins , Before simulation i i i God , The maximum profit in each state .
- b u y 1 buy1 buy1: front i i i The maximum profit of buying only once a day . b u y = max ( b u y ′ , − p r i c e s [ i ] ) buy=\max(buy', -prices[i]) buy=max(buy′,−prices[i]). in other words , It can be before i − 1 i-1 i−1 Make a purchase when the stock price is low ( b u y ′ buy' buy′), You can also not be in front i − 1 i-1 i−1 I bought it on the day i i i Sky buying ( − p r i c e s [ i ] -prices[i] −prices[i]).( Here we use b u y ′ buy' buy′ On behalf of the i − 1 i-1 i−1 days b u y buy buy Value )
- s e l l 1 sell1 sell1: front i i i Once a day . s e l l 1 = max ( s e l l 1 ′ , b u y 1 ′ + p r i c e s [ i ] ) sell1=\max(sell1', buy1' + prices[i]) sell1=max(sell1′,buy1′+prices[i]). in other words , It can be in front i − 1 i-1 i−1 I bought and sold once a day and didn't do anything today ( s e l l 1 ′ sell1' sell1′), It can also be the former i − 1 i-1 i−1 I only bought on the day and on the i i i Day sell ( b u y 1 ′ + p r i c e s [ i ] buy1'+prices[i] buy1′+prices[i])( Selling will make a profit p r i c e s [ i ] prices[i] prices[i])
- b u y 2 buy2 buy2: front i i i Once a day + One time purchase . b u y 2 = max ( b u y 2 ′ , s e l l 1 ′ − p r i c e s [ i ] ) buy2=\max(buy2', sell1'-prices[i]) buy2=max(buy2′,sell1′−prices[i]). in other words , It can be in front i − 1 i-1 i−1 A deal was made on the day + Buy once and do nothing today ( b u y 2 ′ buy2' buy2′), It can also be the former i − 1 i-1 i−1 A sale was made on the day and on the i i i Day bought again ( s e l l 1 ′ + ( − p r i c e s [ i ] ) sell1' + (-prices[i]) sell1′+(−prices[i]))( Buying will cost p r i c e s [ i ] prices[i] prices[i])
- s e l l 2 sell2 sell2: front i i i Two transactions have been made in the past few days . s e l l 2 = max ( s e l l 2 ′ , b u y 2 ′ + p r i c e s [ i ] ) sell2=\max(sell2',buy2'+prices[i]) sell2=max(sell2′,buy2′+prices[i]). It can be in front i − 1 i-1 i−1 I bought and sold twice a day and didn't do anything today ( s e l l 2 ′ sell2' sell2′), It can also be the former i − 1 i-1 i−1 There was only one deal in the past day + Buy once and in the i i i Tian sold and bought for the second time ( b u y 2 ′ + p r i c e s [ i ] buy2'+prices[i] buy2′+prices[i])( Selling will make a profit p r i c e s [ i ] prices[i] prices[i])
therefore , Simulation finished n n n Days later , return s e l l 2 sell2 sell2 that will do ( Two transactions )
Be careful , In the title, there are two transactions at most , That is to say, you can only do one transaction or no transaction . Selling on the same day without buying or selling is equivalent , Therefore, it can be understood that you must buy and sell twice, but you may have sold on the same day you bought .
- Time complexity O ( n ) O(n) O(n)
- Spatial complexity O ( 1 ) O(1) O(1), Only constant extra space is used
AC Code
C++
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy1 = -prices[0], sell1 = 0;
int buy2 = -prices[0], sell2 = 0;
for (int i = 1; i < prices.size(); i++) {
buy1 = max(buy1, 0 + (-prices[i]));
sell1 = max(sell1, buy1 + (prices[i]));
buy2 = max(buy2, sell1 + (-prices[i]));
sell2 = max(sell2, buy2 + (prices[i]));
}
return sell2;
}
};
The code is very short , The key is to strictly follow the definition of variables and understand .
Synchronous posting on CSDN, Originality is not easy. , Reprint please attach Link to the original text Oh ~
Tisfy:https://letmefly.blog.csdn.net/article/details/125889831
边栏推荐
- From the big guy baptism! 2022 headline first hand play MySQL advanced notes, and it is expected to penetrate P7
- Do you need to open an account to buy a wealth management product with a 6% income?
- 2022 最 NB 的 JVM 基础到调优笔记, 吃透阿里 P6 小 case
- UART
- 1. Smoke test
- Sql文件导入数据库-保姆级教程
- Pit record: typeerror:'module'object is not callable
- Discussion on line segment tree
- Notes of Teacher Li Hongyi's 2020 in-depth learning series 5
- 技术操作
猜你喜欢

Qt项目-安防监控系统(各个界面功能实现)

给生活加点惊喜,做创意生活的原型设计师丨编程挑战赛 x 选手分享

Weekly summary (*66): next five years

芯片的功耗

JS ------ Chapter 3 JS cycle

Opengauss kernel analysis: query rewriting

Notes of Teacher Li Hongyi's 2020 in-depth learning series 9

3. Pressure test

See project code Note 1

Add a little surprise to life and be a prototype designer of creative life -- sharing with X contestants in the programming challenge
随机推荐
Qt学习-利用数据库单例完成 登录匹配 + 注册 功能实现
Qt项目-安防监控系统(各个界面功能实现)
Entity service is an anti pattern
codeforces round #805 ABCDEFG
Bug summary
Vite3.0 has been released, can you still roll it (list of new features)
NVIDIA inspector detailed instructions
Go基础笔记_4_map
Shell echo command
Mandatory interview questions: 1. shallow copy and deep copy_ Deep copy
MySQL common basic commands
First experience of flask
线段树杂谈
LeetCode_ 6124_ The first letter that appears twice
必会面试题:1.浅拷贝和深拷贝_深拷贝
Advanced function of postman
Pit record: typeerror:'module'object is not callable
Paper notes: accurate causal influence on discrete data
Add a little surprise to life and be a prototype designer of creative life -- sharing with X contestants in the programming challenge
Development direction and problems of optaplanner