LeetCode 188 Best Time to Buy and Sell Stock IV (动态规划 推荐)

177 篇文章 0 订阅
60 篇文章 0 订阅

Say you have an array for which the ith element is the price of a given stock on dayi.

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

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.


题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/

题目分析:股票系列最后一题,最多买k次,对于两次的时候有这样一种很好理解的解法:

for (int price : prices) {
    sell2 = Math.max(sell2, buy2 + price);
    buy2 = Math.max(buy2, sell1 - price);
    sell1 = Math.max(sell1, buy1 + price);
    buy1 = Math.max(buy1, -price);
}

然后推广的k次,实际上就是加一层循环,有一个优化,如果k >= n / 2,相当于可以买无限次,直接用无限次的做法On扫一下即可
public class Solution {  
    public int maxProfit(int k, int[] prices) {  
        int n = prices.length;  
        if (n < 2) {  
            return 0;  
        }  
        if (k >= n / 2) {  
            int ans = 0;  
            for (int i = 0; i < n - 1; i++) {  
                if (prices[i + 1] > prices[i]) {  
                    ans += prices[i + 1] - prices[i];  
                }  
            }  
            return ans;  
        }  
        else {  
            int[] sell = new int[n + 1];  
            int[] buy = new int[n + 1];  
            for (int i = 1; i <= n; i++) {  
                buy[i] = -0x3fffffff;  
            }  
            for (int i = 0; i < n; i++) {
                for (int j = k; j >= 1; j--) {
                    sell[j] = Math.max(sell[j], buy[j] + prices[i]);  
                    buy[j] = Math.max(buy[j], sell[j - 1] - prices[i]); 
                }  
            }  
            return sell[k];   
        }  
    }  
}  




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值