LeetCode188——买卖股票的最佳时机IV

我的LeetCode代码仓:https://github.com/617076674/LeetCode

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

题目描述:

知识点:动态规划

思路:动态规划

本题是LeetCode123——买卖股票的最佳时机III的加强版,其状态定义和状态转移与LeetCode123——买卖股票的最佳时机III相同,只是在此基础之上多了一个优化:

如果k >= prices.length / 2,说明我们可以随意地买入和卖出,相当于我们的交易次数不受限,这个时候我们没有必要用动态规划来解,只要后一天的价格比前一天高,我们就一定能够获得该价格差的利润值

如果k >= prices.length / 2,时间复杂度是O(n),其中n为prices数组的长度。空间复杂度是O(1)。

否则,时间复杂度是O(kn),其中n为prices数组的长度。空间复杂度是O(n)。

JAVA代码:

public class Solution {
    public int maxProfit(int k, int[] prices) {
        int result = 0;
        if (0 == prices.length || 0 == k) {
            return result;
        }
        if(k >= prices.length / 2){
            for (int i = 1; i < prices.length; i++) {
                if(prices[i] > prices[i - 1]){
                    result += prices[i] - prices[i - 1];
                }
            }
            return result;
        }
        int[][] dp = new int[2][prices.length];
        for(int t = 0; t < k; t++){
            int cur = t % 2;
            int pre = 1 - cur;
            dp[cur][0] = 0;
            int min = prices[0];
            for(int i = 1; i < prices.length; i++){
                dp[cur][i] = Math.max(dp[cur][i - 1], prices[i] - min);
                if(t == 0){
                    min = Math.min(min, prices[i]);
                }else {
                    min = Math.min(min, prices[i] - dp[pre][i - 1]);
                }
            }
            if(result == dp[cur][prices.length - 1]){
                break;
            }
            result = dp[cur][prices.length - 1];
        }
        return result;
    }
}

LeetCode解题报告:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值