LeetCode-Best Time to Buy and Sell Stock III

来源:互联网 发布:天地图框架数据标准 编辑:程序博客网 时间:2024/05/21 06:44

题目描述

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、最开始我用的从后往前推的动态规划,失败告终。
2、百度之,转换思路,将0-n,划分为0 ~ i , (i+1) ~ n两段,这样就可以将问题转化为Best Time to Buy and Sell Stock问题。
3、这道题的关键在于是可以买卖两次,那么不妨这样想,第一次买卖是按照时间顺序的,即我们从第一天开始扫描,记录到今天为止的最低货物价格,然后判定若在今天卖出,是否能够获取更大的利润,记为数组left[day]。而第二次买卖是逆时间顺序的,即从最后一天开始扫描,记录到今天为止的最高货物价格,然后判定若在今天买入,是否能够获取更大的利润,记为数组right[day](因为我们已经知道以后的几天里面最高价格了,这就是Best Time to But and Sell Stock的逆向)。
4、做完以上工作之后,开始遍历left和right,找到left[day]和right[day]相加的最大值。
5、关于采用此种方法是否可能导致两次交易时间发生交叉(即第一买卖:第1天买入,第8天卖出。第二次买卖:第2天买入,第16天卖出)导致不能否符合题目的问题,在第4步已经解决了。left[day]表示到day天之前的最好的一次交易,right[day]表示day天之后的最好的一次交易。二者以day天为分界线,将两次交易隔开了。

代码如下:

public class Solution {    public int maxProfit(int[] prices) {        if(null == prices || 0 == prices.length)        {            return 0;        }        int[] left = new int[prices.length];        int[] right = new int[prices.length];        int min = prices[0];        for(int day = 1; day <= prices.length - 1; ++day)        {            //确定当前最大利润            left[day] = left[day - 1] > prices[day] - min ? left[day - 1] : prices[day] - min;            min = prices[day] < min? prices[day] : min;        }        int max = prices[prices.length - 1];        for(int day = prices.length - 1; day >= 1; --day)        {            //确定当前最大利润            right[day] = right[day - 1] > max - prices[day] ? right[day - 1] : max - prices[day];            max = prices[day] > max? prices[day] : max;        }        int re = 0;        for(int day = 0; day <= prices.length - 1; ++day)        {            re = left[day] + right[day] > re ? left[day] + right[day] : re;        }        return re;    }}
0 0