Best Time to Buy and Sell Stock

Objective:

Find out the lowest point to buy-in and find out the a following hightest point to sell-out. And the maximal profit is equivalent to the max difference between the highest point and lowest point.

Before solving this problem, suggest referring to the "maximum subarray" first. Then you will get an idea how to set the pointer and how to store the "buy" and "sell" variables.

 

class Solution {
    
public:
    int maxProfit(vector<int> &prices) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (prices.empty()) return 0;
        int cur = 0; // the pointer
        int buy = 0; // date to buy
        int sell = 0; // day to sell
        int maxProf = 0; // the maximum profit
        
        for(int i=1;i<prices.size();i++)
        {
            if(prices[i]<prices[cur])
                cur = i;
            else if(prices[i]>prices[cur] && prices[i]-prices[cur]>maxProf)
            {
                buy = cur;
                sell = i;
                maxProf = prices[i]-prices[cur];
            }
            
        }
        
        return maxProf;
    }
};

 

 

posted @ 2013-10-17 02:33  WinsCoder  阅读(160)  评论(0编辑  收藏  举报