其他分享
首页 > 其他分享> > 买卖股票的最佳时机 IV

买卖股票的最佳时机 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}));
    }
}

标签:买卖,int,ret,IV,length,最佳时机,prices,return,dp
来源: https://www.cnblogs.com/tianyiya/p/15407934.html