Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-116

Stock Profit with At Most Two Transactions

Problem

Given daily prices, return the maximum profit from at most two non-overlapping buy-then-sell transactions.

Track four state variables in a single pass: the best first buy, first sell, second buy and second sell. Return 0 when no profitable pair of transactions exists.

Hint

sell1 - p is the effective cost of the second buy after banking the first profit.

Test cases

case 1
in: [[3,3,5,0,0,3,1,4]]
expected: 6
case 2
in: [[1,2,3,4,5]]
expected: 4
case 3
in: [[7,6,4,3,1]]
expected: 0
case 4
in: [[]]
expected: 0
case 5
in: [[1]]
expected: 0
Starter codePython
def max_profit_at_most_two(prices):
    # Your code here
    pass

5 test cases · run your code against them in the editor