123. Best Time to Buy and Sell Stock III ——LeetCode

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

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

Example 1:code

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

Example 2:blog

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:ip

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

 題目大意:與以前的題目相似,不過此次有次數限制。最多兩次買賣,問最大獲利。element

思路:若是將數組拆成兩半,那麼每一半均可以用Best Time to Buy and Sell Stock I 題目中的方式獲取到最大獲利,先後加起來,就是最大獲利。用left[i]表示從0到i的最大獲利,遍歷一遍可求得。用right[i]表示從i到length-1的最大獲利,從右向左遍歷一遍可得到。從左往右遍歷時,一邊找最小price一邊更新max獲利;從右往左遍歷時,一邊找最大price,一邊更新當前max獲利。兩遍遍歷,時間複雜度O(n),討論區還有一遍遍歷的解法,有興趣能夠去看看。it

    public static int maxProfit(int[] prices) {
        if (prices == null || prices.length <= 1) {
            return 0;
        }
        int[] left = new int[prices.length];
        int[] right = new int[prices.length];
        int min = prices[0];
        for (int i = 1; i < prices.length; i++) {
            left[i] = Math.max(prices[i] - min, left[i - 1]);
            min = Math.min(min, prices[i]);
        }
        int max = prices[prices.length - 1];
        int res = 0;
        for (int i = prices.length - 2; i >= 0; i--) {
            right[i] = Math.max(max - prices[i], right[i + 1]);
            max = Math.max(max, prices[i]);
            res = Math.max(left[i] + right[i], res);
        }
        return res;
    }
相關文章
相關標籤/搜索