leetcode--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.

public class Solution {
    /**This is a fundamental problem.<br>
     * The running time is O(n).<br>
     * It can be solved by divide-conquer method too with O(nln n)time
     * @author Averill Zheng
     * @version 2014-06-04
     * @since JDK 1.7
     */ 
    public int maxProfit(int[] prices) {
        int profit = 0;
        int length = prices.length;
        int buyDate = 0, sellDate = 0, tempProfit = 0;
        for(int i = 1; i < length; ++i){
        	if(prices[i] >= prices[sellDate]){
        		tempProfit = prices[i] - prices[buyDate];
        		sellDate = i;
        		profit = (profit < tempProfit) ? tempProfit : profit; 
        	}
        	if(prices[i] < prices[buyDate]){
        		buyDate = sellDate = i;
        		tempProfit = 0;
        	}
        }
        return profit;   
    }
}

  

posted @ 2014-06-06 02:35  Averill Zheng  阅读(133)  评论(0编辑  收藏  举报