leetCode 123. Best Time to Buy and Sell Stock III

本文介绍了一种求解在一维数组中进行至多两次股票买卖以获得最大利润的算法。该算法通过动态规划实现,使用两个数组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).

给一个一维数组,代表每天股票价格,找出交易两次最大的获利选择
例如
Input: [7, 1, 5, 3, 6, 4]
最大为7,即【1,5】=4,【3,6】=3

用dp1[i]记录maxprofit[0,i],
用dp2[i]记录maxprofit[i,len-1]
输出就是max(dp1[i]+dp2[i]), i=0~n-1

public static int maxProfit(int[] prices) {
         int len = prices.length;
         if(len<=1)return 0;
         int max=0;

         int dp1[] = new int[len];
           int curmin= prices[0];
           for(int i=1;i<len;i++){
               max = max < prices[i] - curmin ? prices[i] - curmin : max;
               curmin =  prices[i] < curmin ?  prices[i] : curmin;
               dp1[i] = max;
           }

           int curmax= prices[len-1];
           max=0;
           int dp2[] = new int[len];
           for(int i=len-1;i>=0;i--){
               max = max < curmax-prices[i] ? curmax-prices[i]  : max;
               curmax =  prices[i] > curmax ?  prices[i] : curmax;
               dp2[i] = max;
           }
           max=0;
           for(int i=len-1;i>0;i--){
               max = max < dp1[i]+dp2[i] ? dp1[i]+dp2[i]  : max;

           }
    return max;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值