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

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/86563591

我的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解题报告:

扫描二维码关注公众号,回复: 5005643 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/86563591
今日推荐