public int maxProfit(int k, int[] prices) {
        if (k <= 0 || prices == null) return 0;

        int n = prices.length;
        // when k is big enough, this problem becomes BestTimeToBuyAndSellStockII_122
        int maxProfit = 0;
        if (k >= n / 2) {
            for (int i = 1; i < n; ++i) maxProfit += Math.max(prices[i] - prices[i - 1], 0);
            return maxProfit;
        }

        int[][] dp = new int[k + 1][n];
        for (int i = 1; i <= k; ++i) {
            int localMax = dp[i - 1][0] - prices[0];
            for (int j = 1; j < n; ++j) {
                dp[i][j] = Math.max(dp[i][j - 1], prices[j] + localMax);
                localMax = Math.max(localMax, dp[i - 1][j] - prices[j]);
            }
        }
        return dp[k][n - 1];
    }