LeetCode123. Best Time to Buy and Sell Stock III

本文介绍了一种解决LeetCode上股票买卖最佳时机III问题的方法,通过前后遍历数组记录最大收益,实现两次交易条件下的最大利润计算。
题目链接:

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

题目描述:

用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。最多交易两次,手上最多只能持有一支股票,求最大收益。

思路:

最多交易两次。可以以i天为分界线,一个记录以prices[i]为结尾的最大收益(即i天之前的最大收益,从前往后),一个记录以prices[i]为开头的最大收益(i天之后的最大收益,从后往前)。
preProfit[i]+postProfit[i]为总的最大收益。比较最大收益找出最大值。

代码:
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len=prices.size();
        if(len==0){
            return 0;
        }
        int* preProfit=new int [len];
        int* postProfit=new int [len];
        int minPrice=prices[0];
        preProfit[0]=0;
        for(int i=1;i<len;i++){
            minPrice=min(minPrice,prices[i]);
            preProfit[i]=max(preProfit[i-1],prices[i]-minPrice);
        }
        int maxPrice=prices[len-1];
        postProfit[len-1]=0;
        for(int i=len-2;i>=0;i--){
            maxPrice=max(maxPrice,prices[i]);
            postProfit[i]=max(postProfit[i+1],maxPrice-prices[i]);
        }
        int maxRes=preProfit[0]+postProfit[0];
        for(int i=1;i<len;i++){
            if(maxRes<preProfit[i]+postProfit[i]){
                maxRes=preProfit[i]+postProfit[i];
            }
        }
        return maxRes;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值