10 · Arrays & Strings

#122 Best Time to Buy and Sell Stock II

Mediumsolve on LeetCode ↗

frequently reported atAppleAmazonBloombergGoogleMicrosoft

the problem

In plain words

prices[i] is a stock's price on day i. You may trade as many times as you like, but you can hold at most one share at a time, so you must sell before you buy again. Buying and selling on the same day is allowed. Return the maximum total profit.

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

out 7

Buy at 1, sell at 5 (+4); buy at 3, sell at 6 (+3).

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

out 4

Buy at 1, sell at 5 — the same as adding every one-day rise.

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

out 0

Prices only fall, so never trade.

  • 1 ≤ n ≤ 3·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. #121
      Best Time to Buy and Sell Stock
      Easyin Arrays & Strings
    2. #53
      Maximum Subarray
      Mediumin Arrays & Strings