• Best Time to Buy and Sell Stock IV 解答


    Question

    Say you have an array for which the ith 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.

    For example, given prices = [4,4,6,1,1,4,2,5], and k = 2, return 6.

    Answer

    用DP解答。

    local[i][j] 表示0~i的数,最多j次交易,并且最后一次交易必须包含prices[j](即最后一天必须卖出),收益最大值。

    global[i][j] 表示0~i的数,最多j次交易,收益最大值。

    diff = prices[i] - prices[i-1] local[i][j] = max(global[i-1][j-1] + max(diff,0),local[i-1][j]+diff) global[i][j] = max(local[i][j], global[i-1][j])

    local[i-1][j] + diff 表示第i-1天,买进prices[i-1],第i天卖出。

    由于local[i-1][j]表示最后一次交易必须包含prices[i-1],即prices[i-1]必须卖出。所以可以把第i-1天的交易和第i天的交易合并,即成了最多j次交易,最后一天交易必须卖出prices[i]。 global[i-1][j-1] 表示前i-1天,最多j-1次交易。最后一天比较diff,如果diff>0,则第i-1天买进,第i天卖出;如果diff<0,则第i天买进,第i天卖出。

    class Solution {
        /**
         * @param k: An integer
         * @param prices: Given an integer array
         * @return: Maximum profit
         */
        public int maxProfit(int k, int[] prices) {
            // write your code here
            if (k == 0) {
                return 0;
            }
            if (k >= prices.length / 2) {
                int profit = 0;
                for (int i = 1; i < prices.length; i++) {
                    if (prices[i] > prices[i - 1]) {
                        profit += prices[i] - prices[i - 1];
                    }
                }
                return profit;
            }
            int n = prices.length;
            int[][] mustsell = new int[n + 1][n + 1];   // mustSell[i][j] 表示前i天,至多进行j次交易,第i天必须sell的最大获益
            int[][] globalbest = new int[n + 1][n + 1];  // globalbest[i][j] 表示前i天,至多进行j次交易,第i天可以不sell的最大获益
            
            mustsell[0][0] = globalbest[0][0] = 0;
            for (int i = 1; i <= k; i++) {
                mustsell[0][i] = globalbest[0][i] = 0;
            }
            
            for (int i = 1; i < n; i++) {
                int gainorlose = prices[i] - prices[i - 1];
                mustsell[i][0] = 0;
                for (int j = 1; j <= k; j++) {
                    mustsell[i][j] = Math.max(globalbest[(i - 1)][j - 1] + gainorlose,
                                                mustsell[(i - 1)][j] + gainorlose);
                    globalbest[i][j] = Math.max(globalbest[(i - 1)][j], mustsell[i ][j]);
                }
            }
            return globalbest[(n - 1)][k];
        }
    };
    
  • 相关阅读:
    大数据数仓数据分层名次介绍
    php 解压zip 格式的文件 何苦
    php 命令行执行 何苦
    VSCode使用笔记 何苦
    K8S Cilium网络插件——安装(v1.11.x版本)
    产品
    如何做好餐饮
    写作
    历史
    本能
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/5988961.html
Copyright © 2020-2023  润新知