[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.

 

Have you been asked this question in an interview? 
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size()==0) return 0; //未考虑[]
        int buy=prices[0];
        int max=0;
        for(int i=1;i<prices.size();i++)
        {
            if(prices[i]<buy) buy=prices[i];
            else 
            {
                if(max<(prices[i]-buy)) max=prices[i]-buy;
            }
        }
        return max;
    }
};

  

posted @ 2014-03-09 21:17  七年之后  阅读(123)  评论(0编辑  收藏  举报