LeetCode 123: Best Time to Buy and Sell Stock III

本文提供了一种算法来解决寻找股票买卖的最佳时机问题,允许进行最多两次交易,并确保每次卖出后才能再次购买。通过动态规划的方法,分别从前向后和从后向前计算每个阶段的最大利润,最终得出整体最大利润。

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

Difficulty: 4

Frequency: 2


Problem:

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).

Solution:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (prices.size() < 2)
            return 0;

        int * from_begin = new int[prices.size()];
        int * from_end = new int[prices.size()];
        int i_max_profit = 0, i_min = 0, i_max = 0;
        from_begin[0] = 0;
        from_end[prices.size() - 1] = 0;
        for (int i = 1; i<prices.size(); ++i)
        {
            if (prices[i]>prices[i_max])
            {
                i_max = i;
                i_max_profit = max(i_max_profit, (prices[i_max] - prices[i_min]));
            }
            else if(prices[i]<prices[i_min])
            {
                i_max = i_min = i;
            }
            from_begin[i] = i_max_profit;
        }
        i_max_profit = 0, i_min = i_max = prices.size() - 1;
        for (int i = prices.size() - 2; i>=0; --i)
        {
            if (prices[i]<prices[i_min])
            {
                i_min = i;
                i_max_profit = max(i_max_profit, (prices[i_max] - prices[i_min]));
            }
            else if(prices[i]>prices[i_max])
            {
                i_max = i_min = i;
            }
            from_end[i] = i_max_profit;
        }
        i_max_profit = 0;
        for (int i = prices.size() - 1; i>=0; --i)
        {
            i_max_profit = max(i_max_profit, (from_end[i] + from_begin[i]));//See Notes. This is important.
        }
        delete [] from_begin;
        delete [] from_end;
        return i_max_profit;
    }
};


Notes:

Originally, I wrote max(i_max_profit, from_end[i] + from_begin[i-1]). This has two errors. First is i-1 should be i. Because we can sell it and then buy it in one day. The second is if without a () outside from_end[i] + from_begin[i-1] , it will cause runtime error. I guess it is because max is define as a macro using ?: operator, it has a low priority.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值