2:买卖股票的最佳时机

描述:假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

样例

给出一个数组样例 [3,2,3,1,2], 返回 1

class Solution {  

public:  

    /**

     * @param prices: Given an integer array

     * @return: Maximum profit

     */  

    int maxProfit(vector<int> &prices) {  

        // write your code here  

        if(prices.size() == 0)

        {  

            return 0;  

        }  

          

        int max = 0;  

        int cur = prices[0];  

        for(int i = 0; i < prices.size(); ++i)

        {  

            if(prices[i] < cur)

            {  

                cur = prices[i];  

            }

            else

            {   

                int tmp = prices[i] - cur;  

                if(tmp > max)

                {  

                    max = tmp;  

                }  

            }  

        }  

        return max;  

    }  

};

原文地址:https://www.cnblogs.com/kyoxy/p/6522894.html