Leetcode_Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 从右到左扫描,维护一个当前节点右边最低的股价,用当前股价和最低股价的差作为最大收益交易的候选。扫描一遍,即可得最大收益。

class Solution {
public:
//I
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = prices.size();
        if(len < 2) return 0;
        
        int min = prices[0];
        int res = 0;
        for(int i = 1; i< prices.size(); ++i)
        {    
            if(prices[i] < min){
                min = prices[i] ;
                continue;
            }
            res = res > prices[i] - min ? res : prices[i] - min ;
        }
        
        return res;
    }
};

 

posted @ 2013-09-13 15:53  冰点猎手  阅读(139)  评论(0编辑  收藏  举报