Monday, July 21, 2014

Best time to buy and sell stock -- Leetcode

Question:
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.
Answer:
Follow-up: to print out the start and end day time.

int maxProfit(vector<int> &prices,int &start, int &end) {
        int minv = INT_MAX, maxv = 0, dif = 0, int k;
        for(int i=0;i<prices.size();++i){
            if(prices[i]<minv){
                minv = prices[i];
                k = i;                     //Just to keep previous latest minv index, when maxv updated!      
            }
            dif = prices[i] - minv;
            if(dif> maxv){
                maxv = dif;
                start = k;
                end = i;
            }
        }
        return maxv;
    }

No comments:

Post a Comment