BiruLyu
8/5/2017 - 12:09 AM

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

public class Solution {
    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;
    }
    
    public int maxProfit(int k, int[] prices) {
        if (prices == null || prices.length < 1) return 0;
        int len = prices.length;
        if (k >= len / 2) return quickSolve(prices);
        
        int[][] dp = new int[k + 1][len];
        int res = 0;
        for (int i = 1; i <= k; i++) {
            int tempMax = dp[i - 1][0] - prices[0];
            for (int j = 1; j < len; j++) {
                dp[i][j] = Math.max(dp[i][j - 1], prices[j] + tempMax);
                tempMax = Math.max(tempMax, dp[i - 1][j] - prices[j]);
                res = Math.max(res, dp[i][j]);
            }
        }
        return res;
    }
}