【LeetCode】Best Time to Buy and Sell Stock III

本文探讨了如何使用在线算法解决股票买卖问题,通过避免重复计算来提高效率。重点介绍了如何构建两个序列来记录最大利润,并通过遍历计算最终最大利润。

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

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

这题没做出来,看了网上的分析才做出来的。。。关键点就是要利用on-line算法的性质,避免重复计算。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if (prices.size() < 2) {
            return 0;
        }
        vector<int> max_profile1; max_profile1.reserve(prices.size() + 1); // max_profile1[i] : max profit of [0, i]
        vector<int> max_profile2; max_profile2.reserve(prices.size() + 1); // max_profile2[i] : max profit of [i, end];
        
        max_profile1[0] = 0;
        int low = prices[0], temp = 0;
        for (int i = 1, end = prices.size(); i < end; ++i) {
            if (prices[i] < low ) { low = prices[i]; }
            if (prices[i] - low > temp) { temp = prices[i] - low; }
            max_profile1[i] = temp;
        }
        
        max_profile2[prices.size()] = 0;
        int hi = prices[prices.size()-1]; temp = 0; 
        for (int i = prices.size() - 1; i >= 0; --i) {
            if (hi < prices[i]) { hi = prices[i]; }
            if (temp < hi - prices[i]) { temp = hi - prices[i]; }
            max_profile2[i] = temp;
        }
        
        int max_profile = 0;
        for (vector<int>::size_type i = 0, end = prices.size(); i < end; ++i) {
            if (max_profile < max_profile1[i] + max_profile2[i+1]) {
                max_profile = max_profile1[i] + max_profile2[i+1];
            }
        }
        return max_profile;
    }

};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值