LeetCode 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).
Subscribe to see which companies asked this question.


假設你有一個數組,它的第i個元素是一支給定的股票在第i天的價格。設計一個算法來找到最大的利潤。你最多可以完成兩筆交易。
注意事項
你不可以同時參與多筆交易(你必須在再次購買前出售掉之前的股票)
樣例
給出一個樣例數組 [4,4,6,1,1,4,2,5], 返回 6

solution

Approach ##1 two dp

最多可以進行兩次交易,無非就是賣出之后還要再買進一次。
所以我們用兩個dp數組分別記錄兩次交易的最大收益。

left[i]:表示從第一天到第i天進行一次交易最大的收益
right[i]:表示從第i天到最后一天進行一次交易最大的收益
填滿這兩個動態規劃數組之后,我們直接循環一次,找到最大值就是本題進行兩次交易的答案。

class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        // write your code here
        if (prices == null || prices.length <= 1) {
            return 0;
        }

        int[] left = new int[prices.length];
        int[] right = new int[prices.length];

        // DP from left to right;
        left[0] = 0;
        int min = prices[0];
        for (int i = 1; i < prices.length; i++) {
            min = Math.min(prices[i], min);
            left[i] = Math.max(left[i - 1], prices[i] - min);
        }

        //DP from right to left;
        right[prices.length - 1] = 0;
        int max = prices[prices.length - 1];
        for (int i = prices.length - 2; i >= 0; i--) {
            max = Math.max(prices[i], max);
            right[i] = Math.max(right[i + 1], max - prices[i]);
        }

        int profit = 0;
        for (int i = 0; i < prices.length; i++){
            profit = Math.max(left[i] + right[i], profit);  
        }

        return profit;
    }
};

Approach ##2 dp

可以參考Best Time to Buy and Sell Stock IV的解析,將求出進行k次交易的最大收益,所以只要令其k=2就是本題的解法

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容