LeetCode123——买卖股票的最佳时机III

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

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

题目描述:

知识点:动态规划

思路一:分解成两个LeetCode121——买卖股票的最佳时机子问题

枚举第一笔交易卖出的时间firstDealSell,对[0, firstDealSell]范围内的价格求解LeetCode121——买卖股票的最佳时机中的问题,得到结果result1,再对[firstDealSell, n - 1]范围内的价格再一次求解LeetCode121——买卖股票的最佳时机中的问题,其中n为prices数组的大小,得到结果result2,求result1 + result2的最大值。

时间复杂度是O(n ^ 2)。空间复杂度是O(1)。

当然,在此基础之上,结合LeetCode122——买卖股票的最佳时机II,我们可以做一些小小的优化。

对于第一次和第二次卖出的时间点,firstDealSell和secondDealSell,其之前的价格一定是一个上坡,其之后的价格一定是一个下坡,我们在价格坡顶卖出。

JAVA代码:

public class Solution {
    public int maxProfit(int[] prices) {
        int result = 0;
        if(prices.length == 0){
            return result;
        }
        int firstDealSell;  //第一笔交易在firstDealSell卖出
        int secondDealSell; //第二笔交易在secondDealSell卖出
        for(secondDealSell = prices.length - 1; secondDealSell > 0; secondDealSell--){
            if(prices[secondDealSell - 1] < prices[secondDealSell]){
                break;
            }
        }
        for(firstDealSell = 1; firstDealSell < prices.length; firstDealSell++){
            while(firstDealSell + 1 < prices.length && prices[firstDealSell + 1] >= prices[firstDealSell]){
                firstDealSell++;
            }
            int result1 = maxProfit(prices, 0, firstDealSell);
            int 
  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值