123. Best Time to Buy and Sell Stock III(同小米风口的猪)

本文介绍了一种算法,用于计算给定股票价格数组中通过至多两次买卖交易所能获得的最大利润。该算法首先从前向后遍历数组以确定第一次买入的最佳时机,接着从后向前遍历以确定第二次卖出的最佳时机。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

这道题实际上就是最大差值问题。之一更新最小值或最大值,以及当前最大差值即可。

这道题由于是两次购入,所有分别从左右两端求得然后相加即可。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        const int size = prices.size();

        if(size == 0)
            return res;

        vector<int> vec(size, 0);

        //从左往右计算vec[i](vec1[i])表示,第1..i+1天的最大收益,因为数组下标从零开始
        int min = prices[0];
        for(int i=1; i<size; ++i){
            vec[i] = vec[i-1];   //如果收益没有之前的多,至少要保持
            if(prices[i] - min > vec[i])  //以当天为界限,计算之前的最大收益,所以是减
                vec[i] = prices[i] - min;
            if(prices[i] < min)
                min = prices[i];
        }

        //从右往左计算vec2[i]表示,第i+1天到最后一天的最大收益
        //这里由于采用vec2[i]空间复杂度为O(2n),所以利用profit变量省去vec2[i],直接在vec[i]上相加即可
        int max = prices[size-1], profit = 0;
        for(int i=size-2; i>=0; --i){
            if(max - prices[i] > profit)  //以当天为界,未来的最大收益,则是更远的天数减去更近的天数
                profit = max - prices[i];
            vec[i] += profit;  //在这里直接+=,直接将之前算的某天以前的最大收益和目前某天以后最大收益相加,节省空间复杂度
            if(prices[i] > max)
                max = prices[i];
        }

        for(int i=0; i<size; ++i)  //找出某一天满足最大收益最大
            res = std::max(res, vec[i]);

        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值