Wednesday, March 19, 2014

Leetcode: Best Time to Buy and Sell Stock III

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

Solution

We can calculate the solution to the problem for 1 transaction, so we use dynamic programming calculating the solution to which is the maximum benefit prior and posterior to certain day, afterwards we just have to iterate through the sum of both arrays finding the maximum.

public class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        int previousMin = Integer.MAX_VALUE;
        int nextMax = Integer.MIN_VALUE;
        int[] maxProfitSellBefore = new int[prices.length];
        int[] maxProfitBuyAfter = new int[prices.length];
        for(int i=0; i<prices.length;i++)
        {
            previousMin = Math.min(previousMin,prices[i]);
            maxProfitSellBefore[i] = i>0 ? Math.max(maxProfitSellBefore[i-1], prices[i]-previousMin) : 0;
        }
        for(int i=prices.length-1; i>=0;i--)
        {
            nextMax = Math.max(nextMax,prices[i]);
            maxProfitBuyAfter[i] = i<prices.length-1 ? Math.max(maxProfitBuyAfter[i+1], nextMax-prices[i]) : 0;
        }
        for(int i=0; i<prices.length;i++)
        {
            maxProfit = Math.max(maxProfit, maxProfitSellBefore[i]+maxProfitBuyAfter[i]);
        }
        return maxProfit;
    }
}

No comments :

Post a Comment