13.5 Best Time to Buy and Sell Stock III

来源:互联网 发布:淘宝卖家申请小二介入 编辑:程序博客网 时间:2024/06/10 22:51

Link: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

You may complete at most two transactions.

My thought: This Q should be more similar to  Best Time to Buy and Sell Stock I than to Best Time to Buy and Sell Stock II.

This thought is correct. 

Approach I: DP

Do Best Time to Buy and Sell Stock I twice. One to calculate maxProfit for each position i between [0, i] from left, the other to calculate maxProfit for each position i between [i, n-1] from the end. Then traverse 3rd time to combine the two on the same position i. 

Note: the previous "for" loops are exactly the same as Best Time to Buy and Sell Stock I. 

Time: O(n), Space: O(n) 

public class Solution {    public int maxProfit(int[] prices) {        if(prices == null || prices.length == 0) return 0;        int n = prices.length;        //left max profit [0, i]        int minPrice = prices[0];        int[] leftMaxProfit = new int[n];        for(int i = 1; i < n; i++){            leftMaxProfit[i] = Math.max(leftMaxProfit[i-1], prices[i] - minPrice);            minPrice = Math.min(minPrice, prices[i]);        }        //right max profit [i, n-1]        int maxPrice = prices[n-1];        int[] rightMaxProfit = new int[n];        for(int i = n-2; i >=0; i--){            rightMaxProfit[i] = Math.max(rightMaxProfit[i+1], maxPrice - prices[i]);            maxPrice = Math.max(maxPrice, prices[i]);        }        int result = 0;        for(int i = 0; i < n; i++){            result = Math.max(result, leftMaxProfit[i] + rightMaxProfit[i]);        }        return result;    }}

Approach II: DP (Reference: http://blog.csdn.net/linhuanmars/article/details/23236995)

Time: O(n), Space: O(1). 

public int maxProfit(int[] prices) {    if(prices==null || prices.length==0)        return 0;    int[] local = new int[3];    int[] global = new int[3];    for(int i=0;i<prices.length-1;i++)    {        int diff = prices[i+1]-prices[i];        for(int j=2;j>=1;j--)        {            local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff);            global[j] = Math.max(local[j],global[j]);        }    }    return global[2];}


//don't understand. 

0 0