当前位置:网站首页>Leetcode (122) - the best time to buy and sell stocks II
Leetcode (122) - the best time to buy and sell stocks II
2022-06-26 21:54:00 【SmileGuy17】
Leetcode(122)—— The best time to buy and sell stocks II
subject
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 .
Example 1:
Input :prices = [7,1,5,3,6,4]
Output :7
explain : In the 2 God ( Stock price = 1) Buy when , In the 3 God ( Stock price = 5) Sell when , The exchange will make a profit = 5 - 1 = 4 .
And then , In the 4 God ( Stock price = 3) Buy when , In the 5 God ( Stock price = 6) Sell when , The exchange will make a profit = 6 - 3 = 3 .
The total profit is 4 + 3 = 7 .
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 .
The total profit is 4 .
Example 3:
Input :prices = [7,6,4,3,1]
Output :0
explain : under these circumstances , There is no positive profit from trading , So you can get the maximum profit by not participating in the transaction , The biggest profit is 0 .
Tips :
- 1 1 1 <= prices.length <= 3 ∗ 1 0 4 3 * 10^4 3∗104
- 0 0 0 <= prices[i] <= 1 0 4 10^4 104
Answer key
Method 1 : greedy
Ideas
Because there are no restrictions on the purchase of shares , So the whole problem is equivalent to finding x x x Two disjoint intervals ( l i , r i ] (l_i,r_i] (li,ri] Maximize the following equation
∑ i = 1 x a [ r i ] − a [ l i ] \sum_{i=1}^{x} a[r_i]-a[l_i] i=1∑xa[ri]−a[li]
among l i l_i li Said in the first l i l_i li Sky buying , r i r_i ri Said in the first r i r_i ri Day sell .
At the same time, we note that for ( l i , r i ] (l_i,r_i] (li,ri] The value contributed by this interval a [ r i ] − a [ l i ] a[r_i]-a[l_i] a[ri]−a[li], In fact, it's equivalent to ( l i , l i + 1 ] , ( l i + 1 , l i + 2 ] , … , ( r i − 1 , r i ] (l_i,l_i+1],(l_i+1,l_i+2],\ldots,(r_i-1,r_i] (li,li+1],(li+1,li+2],…,(ri−1,ri] The length of these intervals is 11 The value of the interval and , namely
a [ r i ] − a [ l i ] = ( a [ r i ] − a [ r i − 1 ] ) + ( a [ r i − 1 ] − a [ r i − 2 ] ) + … + ( a [ l i + 1 ] − a [ l i ] ) a[r_i]-a[l_i]=(a[r_i]-a[r_i-1])+(a[r_i-1]-a[r_i-2])+\ldots+(a[l_i+1]-a[l_i]) a[ri]−a[li]=(a[ri]−a[ri−1])+(a[ri−1]−a[ri−2])+…+(a[li+1]−a[li])
therefore The problem can be simplified by look for x x x A length of 1 1 1 The range of ( l i , l i + 1 ] (l_i,l_i+1] (li,li+1] bring ∑ i = 1 x a [ l i + 1 ] − a [ l i ] \sum_{i=1}^{x} a[l_i+1]-a[l_i] ∑i=1xa[li+1]−a[li] Maximize value .
From the perspective of greed, each time we choose to contribute more than 0 0 0 The interval of can maximize the answer , So the final answer is
ans = ∑ i = 1 n − 1 max { 0 , a [ i ] − a [ i − 1 ] } \textit{ans}=\sum_{i=1}^{n-1}\max\{0,a[i]-a[i-1]\} ans=i=1∑n−1max{ 0,a[i]−a[i−1]}
among n n n Is the length of the array .
It should be noted that , The greedy algorithm can only be used to calculate the maximum profit , The calculation process is not the actual transaction process .
Consider the examples in the topic [ 1 , 2 , 3 , 4 , 5 ] [1,2,3,4,5] [1,2,3,4,5], Length of array n = 5 n=5 n=5, Because of all the 1 ≤ i < n 1 \le i < n 1≤i<n There are a [ i ] > a [ i − 1 ] a[i]>a[i-1] a[i]>a[i−1], So the answer is
ans = ∑ i = 1 n − 1 a [ i ] − a [ i − 1 ] = 4 \textit{ans}=\sum_{i=1}^{n-1}a[i]-a[i-1]=4 ans=i=1∑n−1a[i]−a[i−1]=4
however The actual transaction process is not 4 4 4 Second purchase and 4 4 4 Time to sell , But in the 1 1 1 Sky buying , The first 5 5 5 Day sell .
Code implementation
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = 0, size = prices.size();
if(size <= 1) return 0;
for (int i = 1; i < size; i++) {
if (prices[i] > prices[i-1]) {
// It is profitable to sell
ans += (prices[i] - prices[i-1]);
}
}
return ans;
}
};
Leetcode Official explanation :
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = 0;
int n = prices.size();
for (int i = 1; i < n; ++i) {
ans += max(0, prices[i] - prices[i - 1]); // The difference between adjacent two is in descending order +0
}
return ans;
}
};
Complexity analysis
Time complexity : O ( n ) O(n) O(n), among n n n Is the length of the array . We just need to traverse the array once .
Spatial complexity : O ( 1 ) O(1) O(1). You just need constant space to hold a few variables .
Method 2 : Dynamic programming
Ideas
in consideration of 「 You can't participate in multiple transactions at the same time 」, Therefore, after the end of trading every day, there may only be a stock or no stock in hand .
Define the State dp [ i ] [ 0 ] \textit{dp}[i][0] dp[i][0] It means the first one i i i I don't have the maximum profit of the stock in my hand after trading , dp [ i ] [ 1 ] \textit{dp}[i][1] dp[i][1] It means the first one i i i The biggest profit of holding a stock after a day's trading ( i i i from 0 0 0 Start ).
consider dp [ i ] [ 0 ] \textit{dp}[i][0] dp[i][0] Transfer equation of , If there is no stock in hand after trading on this day , Then the possible transition state is that there are no stocks the day before , namely dp [ i − 1 ] [ 0 ] \textit{dp}[i-1][0] dp[i−1][0], Or hold a stock at the end of the previous day , namely dp [ i − 1 ] [ 1 ] \textit{dp}[i-1][1] dp[i−1][1], At this time we have to sell it , And get prices [ i ] \textit{prices}[i] prices[i] Revenue . So in order to maximize revenue , We list the following State transition equation :
dp [ i ] [ 0 ] = max { dp [ i − 1 ] [ 0 ] , dp [ i − 1 ] [ 1 ] + prices [ i ] } \textit{dp}[i][0]=\max\{\textit{dp}[i-1][0],\textit{dp}[i-1][1]+\textit{prices}[i]\} dp[i][0]=max{ dp[i−1][0],dp[i−1][1]+prices[i]}
Consider again dp [ i ] [ 1 ] \textit{dp}[i][1] dp[i][1], Consider the transition state in the same way , Then the possible transfer status is that you have held a stock the previous day , namely dp [ i − 1 ] [ 1 ] \textit{dp}[i-1][1] dp[i−1][1], Or there were no stocks at the end of the previous day , namely dp [ i − 1 ] [ 0 ] \textit{dp}[i-1][0] dp[i−1][0], At this time, we want to buy it , And reduce prices [ i ] \textit{prices}[i] prices[i] Revenue . You can list the following State transition equation :
dp [ i ] [ 1 ] = max { dp [ i − 1 ] [ 1 ] , dp [ i − 1 ] [ 0 ] − prices [ i ] } \textit{dp}[i][1]=\max\{\textit{dp}[i-1][1],\textit{dp}[i-1][0]-\textit{prices}[i]\} dp[i][1]=max{ dp[i−1][1],dp[i−1][0]−prices[i]}
about The initial state , According to the definition of state, we can know that 0 0 0 At the end of the day dp [ 0 ] [ 0 ] = 0 \textit{dp}[0][0]=0 dp[0][0]=0, dp [ 0 ] [ 1 ] = − prices [ 0 ] \textit{dp}[0][1]=-\textit{prices}[0] dp[0][1]=−prices[0].
therefore , We just need to calculate the state from front to back . Because after the end of all transactions , The income from holding shares must be lower than that from not holding shares ( Buy stocks and spend money , crap ), So this time dp [ n − 1 ] [ 0 ] \textit{dp}[n-1][0] dp[n−1][0] The benefits must be greater than dp [ n − 1 ] [ 1 ] \textit{dp}[n-1][1] dp[n−1][1] Of , The final answer is dp [ n − 1 ] [ 0 ] \textit{dp}[n-1][0] dp[n−1][0].
Notice that in the state transfer equation above , The state of each day is only related to the state of the previous day , It has nothing to do with earlier states , So we don't have to store these irrelevant States , Only need to dp [ i − 1 ] [ 0 ] \textit{dp}[i-1][0] dp[i−1][0] and dp [ i − 1 ] [ 1 ] \textit{dp}[i-1][1] dp[i−1][1] Stored in two variables , They calculate dp [ i ] [ 0 ] \textit{dp}[i][0] dp[i][0] and dp [ i ] [ 1 ] \textit{dp}[i][1] dp[i][1] Coexist back to the corresponding variable , So that the second i + 1 i+1 i+1 The state of days can be transferred .
Code implementation
Leetcode Official explanation :
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int dp0 = 0, dp1 = -prices[0];
for (int i = 1; i < n; ++i) {
int newDp0 = max(dp0, dp1 + prices[i]);
int newDp1 = max(dp1, dp0 - prices[i]);
dp0 = newDp0;
dp1 = newDp1;
}
return dp0;
}
};
Complexity analysis
Time complexity : O ( n ) O(n) O(n), among n n n Is the length of the array . Altogether 2 n 2n 2n Status , The time complexity of each state transition is O ( 1 ) O(1) O(1), So the time complexity is zero O ( 2 n ) = O ( n ) O(2n)=O(n) O(2n)=O(n).
Spatial complexity : O ( n ) O(n) O(n). We need to open up O ( n ) O(n) O(n) All States in spatial storage dynamic planning . If space optimization is used , The space complexity can be optimized to O ( 1 ) O(1) O(1).
边栏推荐
- DLA model (classification model + improved segmentation model) + deformable convolution
- 诗尼曼家居冲刺A股:年营收近12亿 红星美凯龙与居然之家是股东
- 不同的子序列问题I
- Test comparison of linear model LN, single neural network SNN, deep neural network DNN and CNN
- MacOS環境下使用HomeBrew安裝[email protected]
- PostgreSQL notes
- 网易云信正式加入中国医学装备协会智慧医院分会,为全国智慧医院建设加速...
- [bug feedback] the problem of message sending time of webim online chat system
- Flutter 中 ValueNotifier<List<T>> 监听问题解决
- 「连续学习Continual learning, CL」最新2022研究综述
猜你喜欢

协同过滤进化版本NeuralCF及tensorflow2实现

CVPR 2022 - Interpretation of selected papers of meituan technical team

在线协作文档综合评测 :Notion、FlowUs、Wolai、飞书、语雀、微软 Office、谷歌文档、金山文档、腾讯文档、石墨文档、Dropbox Paper、坚果云文档、百度网盘在线文档

In 2022, where will the medium and light-weight games go?

YOLOv6:又快又准的目标检测框架开源啦

y48.第三章 Kubernetes从入门到精通 -- Pod的状态和探针(二一)

leetcode:6107. 不同骰子序列的数目【dp六个状态 + dfs记忆化】

YOLOv6:又快又准的目標檢測框架開源啦

VB.net类库(进阶——2 重载)

大龄程序员的一些出路
随机推荐
Leetcode(452)——用最少数量的箭引爆气球
Convolutional neural network (CNN) explanation and tensorflow2 code implementation
在哪家证券公司开户最方便最安全可靠
The latest 2022 research review of "continuous learning, CL"
Kdd2022 𞓜 unified session recommendation system based on knowledge enhancement prompt learning
CVPR 2022 - Interpretation of selected papers of meituan technical team
Shiniman household sprint A shares: annual revenue of nearly 1.2 billion red star Macalline and incredibly home are shareholders
Common concurrent testing tools and pressure testing methods
Is there any risk in registering and opening an account for stock speculation? Is it safe?
vulnhub之DC9
Is it safe to open a stock account with the QR code given by the CICC securities manager? I want to open an account
诗尼曼家居冲刺A股:年营收近12亿 红星美凯龙与居然之家是股东
AI智能抠图工具--头发丝都可见
Configure redis master-slave and sentinel sentinel in the centos7 environment (solve the problem that the sentinel does not switch when the master hangs up in the ECS)
Which platform is the safest for buying stocks and opening accounts? Ask for sharing
Centos7编译安装Redis
DAST black box vulnerability scanner part 5: vulnerability scanning engine and service capability
VB.net类库,获取屏幕内鼠标下的颜色(进阶——3)
Different subsequence problems I
SAP commerce cloud project Spartacus getting started