牛客题霸 [买卖股票的最好时机] C++题解/答案

买卖股票的最好时机

题解:

设两个变量,一个为minn,一个为maxx
当遇到比当前minn还小的价钱时,就更新minn
当与minn大时,就计算如果这个价卖出,赚多少钱,maxx不断更新取最大值
这样,就能保证利益最大化

代码:

class Solution {
public:
    /**
     * 
     * @param prices int整型vector 
     * @return int整型
     */
    int maxProfit(vector<int>& prices) {
        // write code here
        if(prices.empty())return 0;
        int min=prices[0];
        int maxx=0;
        for(int i=1;i<prices.size();i++){
            if(prices[i]<min){
                min=prices[i];
            }
            else maxx=max(maxx,prices[i]-min);
        }
        return maxx;
    }
};
posted @ 2020-11-07 00:03  回归梦想  阅读(102)  评论(0编辑  收藏  举报