Best Time to Buy and Sell Stock III
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 dayi.- 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⁵
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more dynamic programming (dp) problems
- 70Climbing StairsEasysolve
- 121Best Time to Buy and Sell StockEasysolve
- 198House RobberMediumsolve
- 322Coin ChangeMediumsolve
- 300Longest Increasing SubsequenceMediumsolve
- 62Unique PathsMediumsolve
- 1143Longest Common SubsequenceMediumsolve
- 53Maximum SubarrayMediumsolve
- 918Maximum Sum Circular SubarrayMediumsolve
- 139Word BreakMediumsolve
- 120TriangleMediumsolve
- 64Minimum Path SumMediumsolve
- 63Unique Paths IIMediumsolve
- 97Interleaving StringMediumsolve
- 72Edit DistanceMediumsolve
- 221Maximal SquareMediumsolve
- 188Best Time to Buy and Sell Stock IVHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.