Skip to content
Problem 122 · LeetCode 122(opens in a new tab)

Best Time to Buy and Sell Stock II

MediumArrays

You are given prices, where prices[i] is the cost of one share of a stock on day i.

You may trade as many times as you want, but you can own at most one share at any moment. On a single day you may sell the share you have and then buy again. Return the largest total profit you can make. If no trade helps, return 0.

Example 1

Input:  prices = [2, 7, 4, 6, 9, 3]
Output: 10
Why:    buy 2 sell 7 (+5), buy 4 sell 9 (+5)
2 more examples and the constraints

Example 2

Input:  prices = [3, 4, 5, 8]
Output: 5
Why:    one long climb: buy at 3, sell at 8

Example 3

Input:  prices = [9, 6, 5, 2]
Output: 0
Why:    the price only falls, so never buy

Constraints

  • 1 ≤ length of prices ≤ 30,000
  • 0 ≤ each price ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DP: holding or notO(n)
  2. Greedy: add every riseO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 30,000 daysVerdict
DP: holding or notO(n)
Passes; extends to fees and limits
Greedy: add every riseO(n)
Best; shortest to write

n = how many days of prices there are.

Edge cases to test

  • One day. [4] has nothing to sell into; return 0.
  • Prices only fall. [9, 6, 5, 2] has no rise, so the answer is 0, not a loss.
  • Flat prices. [5, 5, 5] has differences of 0; adding them changes nothing.
  • One long climb. [3, 4, 5, 8] gives 5 either as one trade or as three one-day trades.

Common mistakes

  • Solving the one-trade version: returning the single best buy and sell instead of the sum of all rises.
  • Adding negative differences too, which subtracts the drops from the total.
  • In the DP, computing the new hold from the already-updated cash in Java or C++ without a temporary.

How to talk through it

  1. 1Clarify. Is the number of trades unlimited? Can I sell and buy on the same day? Any fee per trade?
  2. 2Set up the states. Each day ends holding a share or not. Write cash and hold transitions; O(n) time and O(1) space.
  3. 3Spot the shortcut. Any climb splits into one-day rises, so profit is the sum of positive differences.
  4. 4Code the greedy. One loop from day 1; add the difference when it is positive.
  5. 5Test out loud. Run a single day, a falling list and one long climb.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?