LeetCode Best Time to Buy and Sell Stock III(dp)

本文介绍了一种使用动态规划解决股票交易问题的方法,旨在找到在最多进行两次交易的情况下获得最大收益的策略。通过定义两个状态数组 dp1 和 dp2 分别表示从起始到当前时刻的最小成本和从当前到结束的最大收益,我们可以有效地计算出最终的最大收益。

摘要生成于 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).

题意:给出一个数组,数组元素表示股票在第i天的股价,最多只能交易两次,求最大收益

思路:动态规划。用dp1(i)表示从0到i的最小股票值。dp2(i)表示从i到n的最大股票值。在求最大收益值时,将第一次收益的最大值加上第二次收益的最大值相加即可。

代码如下:

class Solution
{
    public int maxProfit(int[] prices)
    {
        int len = prices.length;
        if (0 == len) return 0;

        int[] left = new int[len];
        int[] right = new int[len];

        left[0] = prices[0];
        right[len - 1] = prices[len - 1];
        for (int i = 1; i < len; i++)
        {
            left[i] = Math.min(left[i - 1], prices[i]);
        }

        for (int i = len - 2; i >= 0; i--)
        {
            right[i] = Math.max(right[i + 1], prices[i]);
        }

        int ans = 0;
        int tmp = 0;
        for (int i = 0; i < len; i++)
        {
            tmp = Math.max(tmp, prices[i] - left[i]);
            ans = Math.max(ans, tmp + right[i] - prices[i]);
        }
        return ans;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值