假设从第一天开始买入,买入价格设为in,之后的每一天,只要那天比买入价格高就卖出,计算利润profit,若比买入价格in低就设买入价格为此时的股票价格。

由于每次遇到高价就要计算一次利润,和之前的算得的profit进行比较,profit只存最大值,故而一次循环之后profit必然为最大利润。

代码如下:

public:
    /**
     * 
     * @param prices int整型vector 
     * @return int整型
     */
    int maxProfit(vector<int>& prices) {
        // write code here
        int size = prices.size();
        int in = prices[0];
        int profit = 0;
        for(int i = 1; i < size; i++){
            if(prices[i] > in){
                int tmp = prices[i]-in;
                if(tmp > profit){
                    profit = tmp;
                }
            }else{
                if(i < size-1)
                    in = prices[i];
            }
        }
        return profit;
}
};