Best Time to Buy Stock 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 buy one share of the stock and sell one share of the stock, design an algorithm to find the best times to buy and sell.

 

The question is equivalent to the following:

Find i and j that maximizes Aj – Ai, where i < j.
 
O(N2) 的解法:
 
This is not suggested because this method will throw an exception at big data , run time error;
    public int maxProfit(int[] prices) 
    {
        if(prices.length < 2) 
            return 0;
        
        int maxProfitValue = 0;
        
        for(int i = 0;i< prices.length-2;i++)
        {
            for(int j=i+1; j<prices.length-1;j++)
            {
                if(prices[j]-prices[i]>maxProfitValue)
                {
                    maxProfitValue = prices[j]-prices[i];
                }
            }            
        }
        return maxProfitValue;
    }

O(N)解法:

    public int maxProfit(int[] prices) 
    {
        if(prices.length < 1)
        {
            return 0;
        }
        
        int min = Integer.MAX_VALUE,max=0;
        for(int i = 0; i < prices.length; i++)
        {
            max = Math.max(max,prices[i]-min);
            min = Math.min(min,prices[i]);
        }
        
        return max;
    }

 

posted @ 2013-12-29 11:38  Tooood  阅读(176)  评论(0)    收藏  举报