Sunday, June 15, 2014

LeetCode (Python): 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.

class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        previousMin = float("infinity")
        nextMax = float("-infinity")
        maxProfitSellBefore = [0]
        maxProfitBuyAfter = [0] 
        for i in range(0,len(prices)):
            previousMin = min(previousMin, prices[i])
            if i>0:
                maxProfitSellBefore.append(max(maxProfitSellBefore[i-1], prices[i]-previousMin))
        for i in range(len(prices)-1,-1,-1):
            nextMax = max(nextMax, prices[i])
            if i<len(prices)-1:
                maxProfitBuyAfter.insert(0,max(maxProfitBuyAfter[0], nextMax-prices[i]))
        maxBenefit = 0
        for i in range(0,len(prices)):
            maxBenefit = max(maxBenefit, maxProfitSellBefore[i] + maxProfitBuyAfter[i])
        return maxBenefit

No comments :

Post a Comment