Best Time to Buy and Sell Stock

一次遍历,计算每支股票减掉前面的最小值时的值,然后更新可以获得的最大收益,复杂度为O(n)。注意边界条件的判断。

    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(prices.size() == 0 || prices.size() == 1)
            return 0;
        int max = INT_MIN, min = prices[0];
        int i, len = prices.size(), tmp;
        for(i = 1; i < len; i++){
            if(prices[i] < min)
                min = prices[i];
            tmp = prices[i] - min;
            if(tmp > max)
                max = tmp;
        }
        return max;
    }

 

posted on 2013-09-29 09:23  waruzhi  阅读(133)  评论(0编辑  收藏  举报

导航