leetcode-122. 买卖股票的最佳时机 II
题目:
代码:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int maxProfit(vector<int>& prices) {
int pre0=0,pre1=-prices[0];
int now0,now1;
for(int i=1;i<prices.size();i++){
now0=max(pre0,pre1+prices[i]); //当前没有股票,前一天没有股票或者前一天有股票今天卖出
now1=max(pre1,pre0-prices[i]); //当前有股票,前一天没有股票则今天买入或者前一天有股票
pre0=now0;
pre1=now1;
}
return pre0;
}
int main(){
int res;
vector<int> prices;
int n,tn;
cin>>n;
for(int i=0;i<n;i++){
cin>>tn;
prices.push_back(tn);
}
res=maxProfit(prices);
cout<<res;
return 0;
}