188. Best Time to Buy and Sell Stock IV (1)

Link

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

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

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

Example 1:

Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

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

Solution

Refer to 123, but with checking for k > (prices.length/2), we can reduce the problem to 122 in this case.

先做好邏輯設計再針對edge處理

  public int maxProfit(int k, int[] prices) {
      
        //edge case : k==0 and k < prices.length/2 shall be handled first
        if(k==0)
            return 0;
          
         // to avoid the k is extremely big
        if(k > (prices.length/2)){
            return quickSolve(prices);
        }
        
        int[] buyCost = new int[k];
        int[] maxProfits = new int[k];
        
      
        for(int i = 0; i < k; i++){
            buyCost[i] = Integer.MAX_VALUE;
        }
        for(int j = 0; j < prices.length; j++){
            buyCost[0] = Math.min(buyCost[0], prices[j]);
            maxProfits[0] = Math.max(maxProfits[0], prices[j] - buyCost[0]);
            for(int i = 1; i < k; i++ ){
                buyCost[i] = Math.min(buyCost[i], prices[j] - maxProfits[i-1]);
                maxProfits[i] = Math.max(maxProfits[i], prices[j] - buyCost[i]);
            }
        }
        for(int i = k-1; i >= 0; i--){
            if(maxProfits[i] > 0){
                return maxProfits[i];
            }
        }
        return 0;
    }
    
     private int quickSolve(int[] prices) {
        int len = prices.length, profit = 0;
        for (int i = 1; i < len; i++)
            // as long as there is a price gap, we gain a profit.
            if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
        return profit;
    }

Last updated

Was this helpful?