Best Time to Buy and Sell Stock III

Given an array prices where prices[i] is the price of a stock on day i, return the maximum profit you can achieve with at most two transactions. This problem uses a richer recurrence over buy/sell states.

Input Format

prices = stock prices by day

Output Format

maximum profit with at most two transactions

Constraints

  • 1 <= prices.length <= 10^5; 0 <= prices[i] <= 10^5

Examples

Example 1:

Input:

prices = [3,3,5,0,0,3,1,4]

Output:

6

Explanation:

Two profitable transactions yield a total profit of 6.

Example 2:

Input:

prices = [1,2,3,4,5]

Output:

4

Explanation:

Buy once at 1 and sell once at 5 is optimal even with up to two transactions.

Loading...
Best Time to Buy and Sell Stock III