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


Analysis:
The idea is very simple: buy the stock at a lower price and sell it at a higher price in the future.
The easiest way is try to sell the stock from the 2nd day to the last day, and get the highest profit. For each sell day, get the lowest price before and compute the profit. The algorithm contains two loop, one from the second day to the last, and one from the first day to the current sell day. The complexity is O(n^2).

A better way. How to reduce the complexity ? Similar idea as above but pre-compute the minimum value for each day, which means for each day, compute and store the minimum price of the previous days. In this step the complexity is O(n). Then scan all the days to get the max profit,  total complexity is still O(n).

Java

public int maxProfit(int[] prices) {
        if(prices.length==0) return 0;
        int minP = Integer.MAX_VALUE;
        int maxPro = 0;
        for(int i=0;i<prices.length;i++){
        	if(prices[i]<minP) minP = prices[i];
        	if(prices[i]-minP> maxPro) maxPro = prices[i]-minP;
        }
        return maxPro;
    }
c++

int maxProfit(vector<int> &prices) {
        int max=0, minV = INT_MAX;
    int diff;
    for(int i=0; i<prices.size();i++){
        if(prices[i]<minV) minV = prices[i];
        diff = prices[i]-minV;
        if(diff > max)
            max = diff;
    }
    return max;
    }



你可能感兴趣的:(LeetCode,stock)