买卖股票的最佳时机 IV

链接

给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

class Solution {

    private static int all(int[] prices) {
        int ret = 0;
        for (int i = 1; i < prices.length; ++i) {
            ret += Math.max(0, prices[i] - prices[i - 1]);
        }
        return ret;
    }

    public static int maxProfit0(int k, int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }

        int n = prices.length;
        int[][] dp = new int[n][k + 1];

        /**
         * dp[i][j] = dp[i - 1][j]
         * 
         * dp[i][j - 1] + prices[i] - prices[i]
         * dp[i - 1][j - 1] + prices[i] - prices[i - 1]
         * dp[i - 2][j - 1] + prices[i] - prices[i - 2]
         * dp[i - 3][j - 1] + prices[i] - prices[i - 3]
         */

        for (int i = 1; i < n; ++i) {
            for (int j = 1; j <= k; ++j) {

                int max = 0;
                for (int s = 0; s <= i; ++s) {
                    max = Math.max(max, dp[s][j - 1] + prices[i] - prices[s]);
                }

                dp[i][j] = Math.max(dp[i - 1][j], max);

            }
        }

        return dp[n - 1][k];
    }

    public static int maxProfit(int k, int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }

        int n = prices.length;

        if (k >= n / 2) {
            return all(prices);
        }

        int[][] dp = new int[n][k + 1];

        /**
         * dp[i][j] = dp[i - 1][j]
         * 
         * dp[i][j - 1] + prices[i] - prices[i]
         * dp[i - 1][j - 1] + prices[i] - prices[i - 1]
         * dp[i - 2][j - 1] + prices[i] - prices[i - 2]
         * dp[i - 3][j - 1] + prices[i] - prices[i - 3]
         */

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


        return dp[n - 1][k];
    }

    public static void main(String[] args) {
        System.out.println(maxProfit(2, new int[]{2, 4, 1}));
    }
}
上一篇:猿人学web端爬虫攻防大赛赛题解析_第十八题:jsvmp-洞察先机


下一篇:开发必懂的文件加解密