36 · DP Patterns

#123 Best Time to Buy and Sell Stock III

Hardsolve on LeetCode ↗

frequently reported atMicrosoftAmazonGoogleBloomberg

the problem

In plain words

prices[i] is a stock's price on day i. You may complete at most two trades (a trade is a buy followed by a later sell) and you can never hold more than one share. Return the largest total profit.

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

out 6

Buy at 0, sell at 3; then buy at 1, sell at 4: 3 + 3 = 6.

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

out 4

One trade, 1 → 5, is already the best.

in prices = [7,6,4,3,1]

out 0

  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁵

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #188
    2. #121
      Best Time to Buy and Sell Stock
      Easyin Arrays & Strings