123. Best Time to Buy and Sell Stock III

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

一刷
題解:
dp的原理,但是數組長度為常數。
hold[2], sold[2]分別表示:hold[0], hold[1]表示第一次買入, 第二次買入的最小代價,sold[0], sold[1]表示第一,第二次賣出后的最大利潤。
注意,更新順序為sold[0], hold[0], sold[1], hold[1], 因為hold[I]需要根據sold[I]的信息。

public class Solution {
    public int maxProfit(int[] prices) {
        int[] hold = new int[2];
        int[] sold = new int[2];
        Arrays.fill(hold, Integer.MIN_VALUE);
        for(int price : prices){
            sold[0] = Math.max(price + hold[0], sold[0]);
            hold[0] = Math.max(hold[0], -price);//hold the minimum number
            sold[1] = Math.max(sold[1], price + hold[1]);
            hold[1] = Math.max(hold[1], sold[0] - price);
        }
        return sold[1];
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容