leetcode123 Best Time to Buy and Sell Stock III

来源:互联网 发布:宁波seo入门教程 编辑:程序博客网 时间:2024/05/29 12:28

我的leetcode代码已经放入github:https://github.com/gaohongbin/leetcode

题目:

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

翻译:

这个题和leetcode122  Best Time to Buy and Sell Stock II差不多,只是leetcode122允许交易无数次,但是本题最多只允许交易2次。

求在最多交易两次的情况下,最大的利润。


自己的错误思路:

这个题我刚开始的思路是,是不是能计算出赚钱最多的两次交易。然后返回,才发现这样根本就不行。刚开始的思路像leetcode122,当出现一个峰值就把这个峰值当做一个卖出点,认为算作一个交易,找出了两个最大的交易,最后结果却是错误的。

例如:1,2,4,2,5,7,2,4,9

这个例子,如果峰值算出一个卖出点,则1,2,4算作一个交易,转利润3.

2,5,7算作一次交易,转利润5.

2,4,9算作一次交易,转利润7。

找出利润最高的两次交易是5+7=12。

但是没有想到1,2,4,2,5,7算作一次交易,转利润6.

2,4,9算作一次交易,转利润7,则两次交易转6+7=13.

我的思路在这里就算错了。


新的思路:

这个题看了网上的算法,用分治算法,以i为分界点,找出prices[0....i]的利润最大的交易。再找出prices[i.....length-1]的利润的最大交易。

遍历所有的i,找出利润最大的即可。


代码:


被注释掉的,是我以前错误思路下的代码。

代码参考了http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html

public int maxProfit(int[] prices) {          if(prices==null || prices.length<2)        return 0;        //        int length=prices.length;//        int max=0;//        int second=0;//        int maxProfit=0;//        for(int i=1;i<length;i++){//        if(prices[i]-prices[i-1]>=0)//        maxProfit+=prices[i]-prices[i-1];//        if(prices[i]-prices[i-1]<0){//         if(max<maxProfit){//             second=max;//             max=maxProfit;//             }//         else if(second<maxProfit)//         second=maxProfit;//        maxProfit=0;//        }//        }//        if(max<maxProfit){//        second=max;//        max=maxProfit;//        }//        else if(second<maxProfit){//        second=maxProfit;//        }//        return max+second;        int length=prices.length;        int[] firstProfit=new int[length];        int[] secondProfit=new int[length];                int min=prices[0];         //每到一个prices[i],用它减去前面所有元素中最下的那个        for(int i=1;i<length;i++){        min=Math.min(min, prices[i]);        firstProfit[i]=Math.max(firstProfit[i-1], prices[i]-min);        }                int max=prices[length-1];  //每到应prices[i],用后面最大的元素减之        for(int i=length-2;i>=0;i--){        max=Math.max(max, prices[i]);        secondProfit[i]=Math.max(secondProfit[i+1],max-prices[i]);        }                int maxProfit=0;              for(int i=0;i<length;i++){        maxProfit=Math.max(maxProfit, firstProfit[i]+secondProfit[i]);        }        return maxProfit;            }



0 0
原创粉丝点击