Thursday, October 23, 2014

Best Time to Buy and Sell Stock

//Solution: For each element, calculate the max difference with the former elements.
    int maxProfit(vector<int> &prices) {
       if (prices.size() == 0)
            return 0;
        int maxv=0;
        int low=prices[0];
        for(int i=1;i<prices.size();i++)
        {
            low=min(low,prices[i]);
            maxv=max(maxv,prices[i]-low);
        }
        return maxv;
    }

No comments:

Post a Comment