1. 程式人生 > >Best Time to Buy and Sell Stock 最佳時間買入賣出股票(一次買入賣出) @LeetCode

Best Time to Buy and Sell Stock 最佳時間買入賣出股票(一次買入賣出) @LeetCode

題目:

最佳時間買入賣出股票:你有一個數組儲存了股票在第i天的價錢,現在你只能進行一次買入賣出,如何賺的最多

思路:

min記錄最小買入價

maxProfit記錄最大利潤

遍歷array,不斷更新最小買入價,計算更新最大利潤

package Level2;

/**
 * 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 S121 {

	public static void main(String[] args) {

	}
	
	public int maxProfit(int[] prices) {
		// 當沒有任何prices資訊的情況
		if(prices.length == 0){
			return 0;
		}
        int min = prices[0];		// 記錄最小買入價的index
        int maxProfit = 0;			// 記錄最大profit
        
        for(int i=1; i<prices.length; i++){
        	// 更新最小買入價
        	if(prices[i] < min){
        		min = prices[i];
        	}
        	
        	// 計算當前利潤
        	int currentProfit = prices[i] - min;
        	// 如果當前利潤超過最大利潤,更新最大利潤
        	if(currentProfit > maxProfit){
        		maxProfit = currentProfit;
        	}
        }
        
        return maxProfit;
    }

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

採用“區域性最優和全域性最優解法”:

思路是維護兩個變數,一個是到目前為止最好的交易,另一個是在當前一天賣出的最佳交易(也就是區域性最優)。遞推式是local[i+1]=max(local[i]+prices[i+1]-price[i],0), global[i+1]=max(local[i+1],global[i])。這樣一次掃描就可以得到結果,時間複雜度是O(n)。而空間只需要兩個變數,即O(1)。

http://blog.csdn.net/linhuanmars/article/details/23162793

有兩點值得注意:

1 在第i天買入,在i+1天賣出,再在i+1天買入,在i+2天賣出,等效於在i天買入在i+2天賣出:p[i+2]-p[i] = -p[i]+p[i+1]-p[i+1]+p[i+2]

2 如果計算出沒兩天的差值:diff1, diff2, diff3 則此題就轉化為maximum subarray的問題

public class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;
        if(len == 0){
            return 0;
        }
        int[] local = new int[len+1];
        int[] global = new int[len+1];
        
        local[0] = 0;
        global[0] = 0;
        for(int i=1; i<len; i++) {
            int diff = prices[i] - prices[i-1];
            local[i] = Math.max(local[i-1]+diff, Math.max(diff, 0));
            global[i] = Math.max(global[i-1], local[i]);
        }
        
        return global[len-1];
    }
}