Best Time to Buy and Sell Stock III

Hard#123states

You get the price of one share for each day. Make at most two trades, each a buy and a later sell; you hold one share at a time, so the second buy comes after the first sale (the same day is fine). Find the largest total profit, or 0 if no trade pays. Our example: [2, 6, 3, 9, 4, 5] → 10, from 2 → 6 and 3 → 9.

input
prices: the price of a stock day by day, prices[i] on day i.
returns
The largest profit from at most two deals. A deal buys one share and sells it on a later day; the second deal buys no earlier than the first one sells.
constraints
  • 1 ≤ prices.length ≤ 1000
  • 0 ≤ prices[i] ≤ 10⁵
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} prices
 * @return {number}
 */
function maxProfit(prices) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more dynamic programming (dp) problems

Pattern “Dynamic programming (DP)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.