Leetcode 123: Best Time to Buy and Sell Stock III

https://leetcode.com/problems/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).

 

Code

import sys

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        lowest_price = sys.maxint
        profit1 = 0
        max_left_after_profit1 = -sys.maxint
        profit_total = 0
        
        for p in prices:
            lowest_price = min(p, lowest_price)
            profit1 = max(profit1, p - lowest_price)
            max_left_after_profit1 = max(max_left_after_profit1, profit1 - p)
            profit_total = max(profit_total, p + max_left_after_profit1)
        
        return profit_total

 

Idea

Use `profit1` to denote the profit gained from the first transaction. This is similar to what we achieved in the easier problem: https://czxttkl.com/?p=1342. Then `max_left_after_profit1` is the maximum money left in your pocket after you finish the first transaction (buy and sell) and the second buy. 

This method achieves O(N) time complexity and O(1) space.

 

You can also use DP to solve this problem. See the idea here: https://czxttkl.com/?p=990

 

 

Leave a comment

Your email address will not be published. Required fields are marked *