medium +28 pts

Max Profit from Selling Twice

Find the maximum profit from at most two stock transactions.

You are given a list of integers `prices` where `prices[i]` is the price of a given stock on day `i`. Write a function `max_profit_twice(prices: list[int]) -> int` that returns the maximum profit you can achieve from **at most two** transactions. A transaction consists of buying one share on one day and selling it on a later day. You may engage in at most two such transactions, but you cannot buy before selling (i.e., you must sell before you can buy again). You may choose to do zero, one, or two transactions. **Function Signature:** ```python def max_profit_twice(prices: list[int]) -> int: ``` Return the maximum possible profit. If no profitable transaction is possible, return `0`. Implement the function so that it handles large input sizes efficiently. The solution should run in O(n) time and O(n) or O(1) extra space.

Constraints

- The length of `prices` can be up to `10^5`. - Each price is an integer between `0` and `10^5`. - The function should return an integer. - Do not use any external libraries.

Example

```python
>>> max_profit_twice([3, 3, 5, 0, 0, 3, 1, 4])
6
>>> max_profit_twice([1, 2, 3, 4, 5])
4
>>> max_profit_twice([7, 6, 4, 3, 1])
0
>>> max_profit_twice([1])
0
```
28 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about splitting the array into two parts: before a split point and after it.
Compute for each day the maximum profit from a single transaction up to that day.
Compute from the right the maximum profit from a single transaction starting from that day.
Combine the left and right profits to get the best total from two transactions.
Alternatively, simulate the state of having completed 0, 1, or 2 transactions using variables.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.