AcWing 1056. 股票买卖 III
原题链接
简单
作者:
废wù
,
2021-02-28 03:25:21
,
所有人可见
,
阅读 382
#include<bits/stdc++.h>
using namespace std;
int maxProfit(vector<int>& prices) {
int i = 0,j = 0,n = prices.size(),k = 2;
if(n < 2)
return 0;
vector<vector<int>> cash(n, vector<int>(k + 1,0));
vector<vector<int>> hode(n, vector<int>(k + 1,INT_MIN));
for(j = k;j > 0;j--){
cash[i][j] = max(hode[0][j] + prices[i],cash[0][j]);
hode[i][j] = max(hode[0][j],cash[i][j - 1] - prices[i]);
}
for(i = 1;i < n;i++){
for(j = k;j > 0;j--){
cash[i][j] = max(hode[i-1][j] + prices[i],cash[i - 1][j]);
hode[i][j] = max(hode[i-1][j],cash[i - 1][j - 1] - prices[i]);
}
}
return cash[n - 1][k];
}
int main(){
int n,p;
cin >> n;
vector<int>prices(n);
for(int i = 0;i < n;i ++){
cin >> p;
prices[i] = p;
}
cout << maxProfit(prices);
return 0;
}