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

分析:

看到最大利润,首先想到动态规划;

动态规划,我们就要找子问题。

就此问题而言,两手交易,并且两手交易不能交叉,实际上是把数组分成两段,分别求前后两段的最大利润,

假设分割点是k,就是求[ 0, k ] 和 [ k, len-1] 的最大利润,注意,这里k是可以交叉的,因为题意是之多两手交易,如果刚好在k点卖出又买入,就可以认为总共进行了一手买卖。

这样,我们要分别计算每点的最大利润。

[0, k] 最大利润用一个动态规划,

[k, len-1] 最大利润用一个动态规划。

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null || prices.length==0) return 0;
        int max=0;
        int[] left = new int[prices.length];
        int[] right = new int[prices.length];
        process(prices, left, right);
        for(int i=0; i<prices.length; i++)
            max = Math.max(max, left[i]+right[i]);
        return max;
    }
    private void process(int[] prices, int[] left, int[] right){
        left[0]=0;
        int min=prices[0];
        for(int i=1; i<left.length; i++){
            left[i] = Math.max(left[i-1], prices[i]-min);
            min = Math.min(min, prices[i]);
        }
        right[right.length-1]=0;
        int max=prices[right.length-1];
        for(int i=right.length-2; i>=0; i--){
            right[i] = Math.max(right[i+1], max-prices[i]);
            max = Math.max(max, prices[i]);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值