Best Time to Buy and Sell Stock IV

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

Solution:

public class Solution {
    public int maxProfit(int k, int[] prices) {
        
        /* add this part to reduce complexity 
        /* when k is larger than prices.length/2 */
        if(k>=prices.length/2){
            int prf = 0;
            for(int i=1; i<prices.length; i++)
                if(prices[i]>prices[i-1])
                    prf += (prices[i]-prices[i-1]);
            return prf;
        }
        
        
        int[] prf = new int[k+1];
        int[] min = new int[k+1];
        for(int i=0; i<=k; i++) min[i] = Integer.MAX_VALUE;
        
        for(int p : prices){
            for(int i=1; i<=k; i++){
                min[i] = Math.min(min[i], p-prf[i-1]);
                prf[i] = Math.max(prf[i], p-min[i]);
            }
        }
        
        return prf[k];
    }
}
comments powered by Disqus