[Leetcode]123. Best Time to Buy and Sell Stock III

This series of Buy and Sell Stock I~VI on Leetcode is a great practice for Dynamic Programming – State Machine. Therefore I prepared blogs for each of them and hopefully it would help you to understand them better. You can find the relations of them at the bottom and feel free to leave any comments. 

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 (i.e., you must sell the stock before you buy again).

This is a special case of [Leetcode]188. Best Time to Buy and Sell Stock IV when the constraint is you can have K transactions at most when K=1. I’ve put detailed explanations there so feel free to check that post.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        K = 2
        if len(prices) < 2:
            return 0
        dp = [0] * (K+1)
        low = [prices[0]] * (K+1)
        for i in range(1,len(prices)):
            for k in range(1,K+1):
                low[k] = min(low[k],prices[i]-dp[k-1])
                dp[k] = max(dp[k],prices[i]-low[k])
        return dp[-1]


Relations among this series problems of ‘buy and sell stock’.
Notify of
Inline Feedbacks
View all comments