You are given an array prices where prices[i] is the price of a given stock on day i (0-indexed).
You want to maximize your profit by choosing when to buy and sell this stock, subject to the constraints below. You may not hold more than one share at a time (i.e., you must sell before you can buy again).
Assume:
1 <= n <= 10^5
, where
n = prices.length
.
0 <= prices[i] <= 10^4
.
You are allowed to complete at most one transaction (i.e., buy once and sell once).
0
.
Example
prices = [7, 1, 5, 3, 6, 4]
5
Now you are allowed to complete at most two transactions.
Return the maximum total profit you can achieve with at most two transactions.
Example
prices = [3, 3, 5, 0, 0, 3, 1, 4]
6
Design algorithms for both parts that run in O(n) time and O(1) or O(n) extra space.