题解 | #买卖股票的最好时机(三)#

买卖股票的最好时机(三)

https://www.nowcoder.com/practice/2fea2b0349df4f7689f6f5a882e4f129

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

class Solution{
public:
    int solve(vector<int>& prices) {
        int sell1 = 0, buy1 = 0, sell2 = 0, buy2 = 0;
        buy1 = -prices[0];  //在第0天进行第一次买入操作,收益
        buy2 = -prices[0];  //在第0天进行第二次买入操作,收益
        
        for (int i = 1; i < (int) prices.size(); ++i) {
            buy1 = max(buy1, -prices[i]);           //在第i天进行第一次买入操作,最大收益。
            sell1 = max(sell1, buy1 + prices[i]); //在第i天进行第一次卖出操作,最大收益。
            buy2 = max(buy2, sell1 - prices[i]);  //在第i天进行第二次买入操作,最大收益
            sell2 = max(sell2, buy2 + prices[i]); //在第i天进行第二次卖出操作,最大收益。
        }
        
        return sell2 > 0 ? sell2 : 0;
    }
};

int main() {
    int n;
    cin >> n;
    vector<int> prices(n, 0);
    for(int i = 0; i < n; ++i)
        cin >> prices[i];
    
    Solution * s = new Solution();
    int ret = s->solve(prices);
    
    cout << ret << endl;
    
    return 0;
}
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务