【LeetCode】123.Best Time to Buy and Sell Stock III(cpp)

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

题目省略233

这是一个牺牲空间复杂度来换取时间复杂度的例子。

买卖股票的题目在LeetCode中有一整个系列(有很多博客在写,很容易搜到)。这道题目是规定最多买卖两次,而第121道题要求只能买一次。我们可以从121中获得一部分思路。

121的思路:遍历数组,一方面计算当前的最优收益,与最高收益做比较;另一方面记录股票的最低价,便于与日后做比较。

代码如下:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int length = prices.size();
        if(length<2)
            return 0;
        int curmin = prices[0];
        int maxProfit = 0;
        for(int i=1; i<length; i++){
            maxProfit = max(maxProfit, prices[i]-curmin);
            curmin = min(curmin, prices[i]);
        }
        return maxProfit;
    }
};

回到123题,要求最多交易两次。比较容易想到把原数组分为两个部分,0-pivot和pivot-prices.size()-1,分别对两个子数组求交易一次的最大收益,再求和。pivot从0遍历到末尾要一次循环,内部要计算子数组的最大收益是O(n)的复杂度,则该算法的复杂度为O(n^2)。代码如下:

class Solution {
public:
    int maxSubArray(vector<int>& prices, int begin, int end){
        int curMin = prices[begin];
        if(end-begin<1)
            return 0;
        int maxProfit = 0;
        for(int i=begin+1; i<=end; i++){
            maxProfit=max(maxProfit, prices[i]-curMin);
            curMin = min(curMin, prices[i]);
        }
        return maxProfit;
    }
    
    int maxProfit(vector<int>& prices) {
        if(prices.size()<2)
            return 0;
        int maxProfit = 0;
        for(int pivot=0; pivot<prices.size()-1; pivot++)
            maxProfit = max(maxProfit, maxSubArray(prices, 0, pivot)+maxSubArray(prices, pivot, prices.size()-1));
        return maxProfit;
    }
};

很不幸,Time Limit Exceeded

仔细想一下,我们遍历的次数太多了,能不能减少遍历次数,开辟一些空间把结果保存起来最后处理?

用一个数组former[]来记录0-pivot天的最大收益,另一个数组later[]记录pivot-末尾的最大收益,用两次遍历可以分别计算出这两个数组。再最后遍历一次这两个数组,找出对应元素和的最大值。

代码如下:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int length = prices.size();
        if (length<2){
            return 0;
        }
        vector<int> former(length,0);
        vector<int> later(length,0);
        int curMin = prices[0];
        int curProfit = 0;
        for(int i=1; i<length; i++){
            curProfit = max(curProfit, prices[i]-curMin);
            curMin = min(curMin, prices[i]);
            former[i] = curProfit;
        }
        int curMax = prices[length-1];
        curProfit = 0;
        for(int i = length-2; i>=0; i--){
            curProfit = max(curProfit, curMax-prices[i]);
            curMax = max(curMax, prices[i]);
            later[i] = curProfit;
        }
        int maxProfit = 0;
        for(int i=0; i<length; i++)
            maxProfit = max(maxProfit, former[i]+later[i]);
        return maxProfit;
    }
};

划重点:用空间复杂度换取时间复杂度,记录中间结果,减少遍历次数。

LeetCode-123. Best Time to Buy and Sell Stock III [C++][Java] Find the maximum profit you can achieve. You may completeat most two transactions. Note:You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). 阅读详情

相关推荐

Leetcode 123. Best Time to Buy and Sell Stock III (Hard) (cpp)

Leetcode 123. Best Time to Buy and Sell Stock III (Hard) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 796

LeetCode - 123. Best Time to Buy and Sell Stock III - 思路详解 - C++

假设一个数组,表示第i天的股票价格。设计算法,求出最大收益,最多可以进行两次交易

SJWL2012的专栏 436

[LeetCode Python3/C++]123. Best Time to Buy and Sell Stock III

Python3 Solution: class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices) == 0: return 0 dp10, dp11, dp20, dp21 = 0, -prices[0], 0, -prices[0] for i in range(len(prices)): tmp = d

xvrixingkong的博客 96

leetcode_c++:Best Time to Buy and Sell Stock III123

题目Say you have an array for which the ith element is the price of a given stock on day i.Design an algorithm to find the maximum profit. You may complete at most two transactions.算法题意:用一个数组表示股票每天的价格,数组

LandscapeMi 239

leetcode_[python/C++]_121/122/123/188.Best Time to Buy and Sell Stock I/II/III/IV

121. Best Time to Buy and Sell Stock [题目] Say you have an array for which the ith element is the price of a given stock on day i.If you were only permitted to complete at most one transaction (ie, bu

Mosen 605

LeetCode 123. Best Time to Buy and Sell Stock III(动态规划)

题目来源:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 问题描述 123.Best Time to Buy and Sell Stock III Hard Say you have an array for which theithelement is the price of a given st...

da_kao_la的博客 341

Leetcode 123 Best Time to Buy and Sell Stock III 至多两次买卖股票最大收益

假设你有一个数组,里面记录的是每一天的股票的价格。 设计一个算法来计算最大收益。你至多可以完成两次交易

(ง •̀_•́)ง 6534

leetcode 123. Best Time to Buy and Sell Stock III 股票最多两次买入、两次卖出的最大利润

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 数组的最大2子段和,允许在一天内买入又卖出,相当于不交易。因为题目规定的是最多交易两次,而不是必须交易两次。 class Solution { public: int maxProfit(vector<int>& prices)...

rock4you 308

123. Best Time to Buy and Sell Stock III***

123. Best Time to Buy and Sell Stock III*** https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 题目描述 Say you have an array for which the ith element is the price of a given stock on day...

珍妮的选择的博客 317

leetcode Best Time to Buy and Sell Stock专题

最佳时间买卖股票问题在leetcode中出现了很多次,并且这些题目之间也具有相似性,所以我将它们做成一个专题来进行总结。 121. Best Time to Buy and Sell Stock 题目: Say you have an array for which the ithi^thith element is the price of a given stock on day iii. I...

qq_29579431的博客 227

leetcode Best Time to Buy and Sell Stock I II III

这三个题目是连续的就一同写下自己的想法吧。 题目1: Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one an

guoxiaozhu的专栏 1571

LeetCode 股票买卖系列 best time to buy and sell stock

LeetCode 股票买卖系列 best time to buy and sell stock

andyL_05的博客 534

LeetCode OJ:Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock III   Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete

王川的私房菜 1198

leetcode 123. Best Time to Buy and Sell Stock III

123.Best Time to Buy and Sell Stock III Hard 98953FavoriteShare Say you have an array for which theithelement is the price of a given stock on dayi. Design an algorithm to find the maximum pro...

cmy203的博客 201

LeetCode123:Best Time to Buy and Sell Stock III

题目: Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: ...

diehuojiang5959的博客 298

[leetcode] 123. Best Time to Buy and Sell Stock III

Description Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You...

Learning from the mistakes 218

Leetcode Best Time to Buy and Sell Stock III

题目: Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note:

HandsomeChow的博客 340

LeetCodeBest Time to Buy and Sell Stock III

纯转载…… 和前两道题比起来的话,这道题最难了,因为限制了交易次数。 解决问题的途径我想出来的是:既然最多只能完成两笔交易,而且交易之间没有重叠,那么就divide and conquer。 设i从0到n-1,那么针对每一个i,看看在prices的子序列[0,...,i][i,...,n-1]上分别取得的最大利润(第一题)即可。 这样初步一算,时间复杂度是O(n2)

ice4026的专栏 432

LeetCodeBest Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You

angelina525的专栏 675
上一篇: 【LeetCode】867. Transpose Matrix
下一篇: 【Leetcode】19. Remove Nth Node From End of List (cpp)
Kir_illo
博客等级 码龄9年 0粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值