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

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

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;
}
全部评论

相关推荐

05-12 11:09
已编辑
门头沟学院 后端
已注销:没必要放这么多专业技能的描述。这些应该是默认已会的,写这么多行感觉在凑内容。项目这块感觉再包装包装吧,换个名字,虽然大家的项目基本都是网上套壳的,但是你这也太明显了。放一个业务项目,再放一个技术项目。技术项目,例如中间件的一些扩展和尝试。
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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