Best Time to Buy and Sell Stock III

You are given an array prices where prices[i] is the price of a given stock on the i^th day.

Find the maximum profit you can achieve. You may complete at most two transactions.

Note: You may not engage in multiple transactions simultaneously; you must sell the stock before you buy again.

Example 1
Inputprices = [3,3,5,0,0,3,1,4]
Output6
Buy on day 4 at price 0 and sell on day 6 at price 3 for profit 3, then buy on day 7 at price 1 and sell on day 8 at price 4 for profit 3, totaling 6.
Example 2
Inputprices = [1,2,3,4,5]
Output4
Buy on day 1 at price 1 and sell on day 5 at price 5 for profit 4; you cannot hold multiple transactions at the same time, so you must sell before buying again.

Constraints

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

Asked at 14 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate