LeetCode--Best Time to Buy and Sell Stock III (動態規劃)

Best Time to Buy and Sell Stock III

 
Total Accepted: 8979 Total Submissions: 40808My Submissions

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Have you been asked this question in an interview?


解題思路:

題目規定最多兩次交易,而不一定是兩次交易。若爲一次交易可以視爲在中間某一天賣出有買進。

動態規劃形式化分析:

設狀態函數 f(i) 表示數組下標區間[0,i] 的最大利潤; 狀態函數g(i) 表示數組下標區間[i,n-1]的最大利潤; 其中 0<= i <= n-1 。

則最終答案爲max{ f(i) + g(i) }, 0<= i <= n-1。 


狀態函數f(i) 的轉換函數爲: f(i) = max( f(i-1), prices[i] - curMin);  //curMin  表示prices數組0 - (i-1) 下標中值的最小值。

狀態函數f(i) 的轉換函數爲: g(i) = max( g(i+1), curMax-prices[i]); //curMax 表示prices數組i - (n-1) 下標中值的最大值。 


備註:

若將原數組變成差分數組,本題就可以看做是最大m子段和(其中m=2)的問題。



程序源代碼:

Java源代碼:


    public int maxProfit(int[] prices) {
        if (prices.length < 2) {
			return 0;
		}
		int[] f = new int[prices.length];
		f[0]=0;
		for (int i = 1, curMin = prices[0]; i < prices.length; ++i) {
				f[i]=Math.max(prices[i]-curMin, f[i-1]); 
				curMin = Math.min(curMin, prices[i]);    
		}
		int[] g= new int[prices.length];
		g[prices.length-1]=0;
		for(int i=prices.length-2,curMax=prices[prices.length-1]; i>-1; --i){
			g[i]=Math.max(g[i+1], curMax-prices[i]);
			curMax= Math.max(curMax, prices[i]);
		}
		int maxProfit = 0;
		for( int i=0; i<prices.length; ++i){
			maxProfit = Math.max(maxProfit, f[i]+g[i]);
		}
		return maxProfit;
	}


附錄:

相關題目:

LeetCode--Best Time to Buy and Sell Stock (貪心策略 or 動態規劃)

LeetCode -- Best Time to Buy and Sell Stock II (貪心策略,差分序列)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章