打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
0188. Best Time to Buy and Sell Stock IV (H)

Best Time to Buy and Sell Stock IV (H)

题目

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Notice that you may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. 

Constraints:

  • 0 <= k <= 10^9
  • 0 <= prices.length <= 10^4
  • 0 <= prices[i] <= 1000

题意

股票买卖问题之四,允许最多k次交易(k次买入k次卖出)。

思路

解法在 0309. Best Time to Buy and Sell Stock with Cooldown 的基础上增加一个k次交易的限制。

\(hold[i][j]\)表示在第i天仍持有股票,且最多已进行了j次交易。
\(sold[i][j]\)表示在第i天未持有任何股票,且最多已进行了j次交易。

可以得到如下递推关系:

\[\begin{cases} hold[i][j]=max(sold[i-1][j-1]-prices[i],\ hold[i-1][j])\\\sold[i][j]=max(hold[i-1][j]+prices[i],\ sold[i-1][j]) \end{cases} \]

边界条件是:\(\forall{j\ge1},\ hold[0][j]=-prices[0]\)

需要注意的是,case可能会使坏给一个巨大的k值,导致超时。这里的一个技巧是,当k大于数组长度一半时时,问题就等同于可以进行不限次数的交易,可以直接用 0122. Best Time to Buy and Sell Stock II 中的一次遍历方法解决。


代码实现

Java

class Solution {
    public int maxProfit(int k, int[] prices) {
        if (prices.length == 0) {
            return 0;
        }

        if (k > prices.length / 2) {
            return maxProfit(prices);
        }

        int[][] hold = new int[prices.length][k + 1];
        int[][] sold = new int[prices.length][k + 1];

        for (int i = 0; i < prices.length; i++) {
            for (int j = 1; j <= k; j++) {
                if (i == 0) {
                    hold[i][j] = -prices[i];
                } else {
                    hold[i][j] = Math.max(hold[i - 1][j], sold[i - 1][j - 1] - prices[i]);
                    sold[i][j] = Math.max(hold[i - 1][j] + prices[i], sold[i - 1][j]);
                }
            }
        }

        return sold[prices.length - 1][k];
    }

    private int maxProfit(int[] prices) {
        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;
    }
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
[LeetCode] Best Time to Buy and Sell Stock I II III IV | 梁佳宾的网络日志
算法 - 如何从股票买卖中,获得最大收益
626,买卖股票的最佳时机 III(动态规划解决)
Sell的相关英语短语和例句:sell out; sell up; sell off等
EA 小代码
英语词汇的来龙去脉45:be sold on什么意思?
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服