LeetCode 123 Best Time to Buy and Sell StockIII

本文介绍了一种通过动态规划算法解决股票交易中最多进行两次买卖以获取最大收益的问题。通过预处理数组记录左侧和右侧的最大收益,最终遍历计算得出最大利润。
题目


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

最多买卖两次,求最大收益值

思路


1  一开始的思路是这样的:和买卖一次的情形差不多,我只要计算出局部最大和第二大的收益值,最后加一下就可以得到答案。但是这个直觉有漏洞。考虑1,2,4,2,5,7,2,4,9,0,局部最大可以是5(7-2)和7(9-2) 也可以是6(7-1)和7(9-2),我这样的思路是没有办法把这个给区分出来的。

2 理性来说,上述我的想法错误在于我考虑用贪心算法来处理这道题目。可是这道题目适合的做法是动态规划。

3 每次看到两次,两个这样,就考虑区分左右区间,或者上下区间。

4 开两个数组,lmax,rmax,lmax的每个点分别代表此点左边最大收益;rmax代表右边最大收益。最后只要遍历一下就行了。

5 求这两个数组的每个点可以由之前或者之后的点来退出,和买卖一次的情形一样

6 我是参考这个http://blog.youkuaiyun.com/pickless/article/details/12034365 来写出代码的。


代码


public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length<=1){
            return 0;
        }
     
       int maxprofit = 0;
       int n = prices.length;
       int[] lmax = new int[n];
       int[] rmax = new int[n];
       
       useme(prices,lmax,rmax,n);
       
       for(int i=0;i<n;i++){
           maxprofit = Math.max(maxprofit,lmax[i]+rmax[i]);
       }
       return maxprofit;
    }
    
    public void useme(int[] prices,int[] lmax,int[] rmax,int n){
        lmax[0]=0;
        int buy = prices[0];
        for(int i=1;i<n;i++){
            lmax[i]=Math.max(lmax[i-1],prices[i]-buy);
            buy = Math.min(buy,prices[i]);
        }
        
        rmax[0] = 0;
        int sell = prices[n-1];
        for(int i = n-2;i>=0;i--){
            rmax[i]=Math.max(rmax[i+1],sell-prices[i]);
            sell = Math.max(sell,prices[i]);
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值