[InterviewBit] Best Time to Buy and Sell Stocks III

Best Time to Buy and Sell Stocks III

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
int Solution::maxProfit(const vector<int> &A) {
if(A.size() < 2) return 0;
vector<long long> dp(A.size() + 2, INT_MIN), dpp(A.size() + 2,INT_MIN);
long long ma = A.back(), res = 0;
for(int i = A.size() - 2; i >= 0; i--) {
dp[i] = max(dp[i+1], ma - A[i]);
dpp[i] = max(dpp[i + 1], dp[i+2] + A[i + 1]);
ma = max(ma,1ll*A[i]);
res = max(res, dpp[i] - A[i]);
}
return max(res,dp[0]);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/29/PS/interviewbit/best-time-to-buy-and-sell-stocks-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.