Best Time to Buy and Sell Stock III 解题思路&代码

来源:互联网 发布:淘宝图片空间全部删除 编辑:程序博客网 时间:2024/05/17 05:51

生平第一次leetcode测试拿到击败全国100%的用户,有点小激动就来写篇博客纪念下。

原题:

Say you have an array for which the ith element is the price of a given stock on dayi.

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天的股票价格是prices[i],一共让我们买两次,求最大可以取得的收益。

解题思路:

首先,这两次交易不能重合,就是说必须在第一次买的股票卖掉之后再买第二次。当然第一次卖出和第二次买入可以是同一天。

所以我们的思路就是,站在某一天上,看一下这一天之前可以获得的最大收益,和这一天以后可以获得的最大收益。

先上代码:

    public static int maxProfit(int[] prices) {
        if(prices.length <=0) return 0;
        int len = prices.length;
        int max = Integer.MIN_VALUE;
        
        int[] maxLeft = new int[len];
        int[] maxRight = new int[len];
        maxLeft[0] = 0;
        maxRight[len-1] = 0;
        
        int lowPoint = prices[0];
        
        for(int i=1;i<len;i++)
        {
            if(prices[i]<lowPoint) lowPoint = prices[i];
            maxLeft[i] = Math.max(maxLeft[i-1],prices[i]-lowPoint);
        }
        
        int highPoint = prices[len-1];
        for(int i=len-2;i>=0;i--)
        {
            if(highPoint<prices[i]) highPoint = prices[i];
            maxRight[i] = Math.max(maxRight[i+1], highPoint-prices[i]);
        }
        
        for(int i=0;i<len;i++)
            max = Math.max(max, maxLeft[i]+maxRight[i]);
        return max;
        
    }


建了两个新数组,长度和prices[]一样,分别储存在i位置左边的最大收益和i位置右边的最大收益,最后maxLeft[i]和maxRight[i]加起来最大的值就是买两次的最大收益。这就是主要的思路。

当计算左边的最大收益时,让i依次往右扫,并把途中遇到的最小值存在lowPoint里,然后用当前价格减去lowPoint,如果收益大于maxLeft[i-1],就存入maxLeft[i],否则就往maxLeft[i]中存入maxLeft[i-1]。

当计算右边最大收益时,原理和上面差不多,只不过是从右往左扫,记录最高价格highPoint。

最后来个循环,求得两者和为最大返回即可。

0 0
原创粉丝点击