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

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

https://www.nowcoder.com/practice/fbc5dad3e215457fb82a3ae688eb7281

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

using namespace std;

class Solution{
public:
    int solve (vector<int>& prices) {
        int sell = 0, buy = 0;
        sell = 0;     //第0天卖股票的收益
        buy = -prices[0]; //第0天买股票的收益
        
        for (int i = 1; i < (int)prices.size(); ++i) {
            buy = max(sell - prices[i], buy); //第i天买股票的最大收益
            sell = max(sell, buy + prices[i]);//第i天卖股票的最大收益
        }
        
        return sell > 0 ? sell : 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;
}
全部评论

相关推荐

09-22 22:22
中山大学 Java
双尔:赌对了,不用经历秋招的炼狱真的太好了,羡慕了
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务