LEETCODE: 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.


有点难,不过和II的解法是一样的,不过要做两次扫描,从左往右,再从右往左。


class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int profit = 0;
        if (prices.size() == 0) {
            return 0;
        }
        vector<int> lefts(prices.size());
        vector<int> rights(prices.size());
        // Scan from left to right, to find current max gap from 0 to ii,
        // and store them in lefts.
        int min = prices[0];
        for (int ii = 1; ii < prices.size(); ii ++) {
            lefts[ii] = std::max(prices[ii] - min, lefts[ii - 1]);        
            min = std::min(prices[ii], min);
        }
        // Scan from right to left, to find current max gap from ii to size - 1,
        // and store them in rights.
        int max = prices[prices.size() - 1];
        for (int ii = prices.size() - 2; ii >= 0; ii --) {
            rights[ii] = std::max(max - prices[ii], rights[ii + 1]);
            max = std::max(prices[ii], max);
        }
        
        // Find the max sum of lefts and rights.
        for (int ii = 0; ii < prices.size(); ii++) {
            profit = std::max(lefts[ii] + rights[ii], profit);
        }
        return profit;      
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值