Skip to content

Practice Best Time to Buy and Sell Stock II

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#122
LeetCode Problem

Best Time to Buy and Sell Stock II

Problem Statement

You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.

Source: Best Time to Buy and Sell Stock II on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
prices = [7,1,5,3,6,4]
Output
7

# Example 2

Input
prices = [1,2,3,4,5]
Output
4

# Example 3

Input
prices = [7,6,4,3,1]
Output
0

Constraints

1 <= prices.length <= 3 * 10^4
0 <= prices[i] <= 10^4

How to solve Best Time to Buy and Sell Stock II

Original notes for interview preparation, written for this problem. Reviewed .

Key insight

With unlimited trades and at most one share, every upward move from one day to the next can be captured on its own, and holding through a dip is never better than selling before it and buying back after. The answer is simply the sum of all positive day-to-day differences.

Why brute force is not enough

Enumerate every way to partition the days into non-overlapping buy and sell pairs, which is exponential, or run a dynamic program over the last sale day that compares every earlier buy day, which is O(n^2). With prices.length up to 3 * 10^4 the quadratic version is about 9 * 10^8 steps.

Approach

  1. Observe that a climb spanning several days equals the sum of its daily increases, so splitting a long hold into one-day trades loses nothing, while a dip inside a hold is pure loss that splitting avoids.
  2. Scan from the second day. Whenever today's price exceeds yesterday's, add the difference to the running profit. Invariant: the running profit equals the maximum achievable using only days seen so far.
  3. On flat or falling days add nothing.
  4. Return the total.
  5. If the interviewer wants a generalizable framing, describe the two-state dynamic program, holding versus not holding a share, which yields the same number and extends to fees and cooldowns.

Walkthrough of Example 1

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

  1. From 7 to 1 the price falls by 6: add nothing, profit 0.
  2. From 1 to 5 the price rises by 4: profit becomes 4.
  3. From 5 to 3 the price falls by 2: add nothing.
  4. From 3 to 6 the price rises by 3: profit becomes 7.
  5. From 6 to 4 the price falls by 2: add nothing. Return 7, equivalent to buying at 1, selling at 5, buying at 3, selling at 6.

Time and space

Time O(n) · Space O(1). n is prices.length; one pass over adjacent pairs with a single accumulator.

Interview pitfalls

  • Hunting for explicit valleys and peaks with nested index loops; it gives the same answer with far more edge cases around plateaus and the final day.
  • Adding negative differences as well as positive ones, which collapses the result to the last price minus the first.
  • Treating a same-day buy and sell as a special case; it contributes zero and needs no handling.
  • Assuming you may hold several shares at once; the one-share limit is what makes the per-day decomposition valid.
  • Forgetting that strictly decreasing or single-day inputs return 0.

Follow-up questions interviewers ask

  • Add a per-transaction fee or a one-day cooldown after selling; why does the greedy break and what state does the dynamic program need?
  • Limit the number of transactions to k and describe how the solution changes.
  • Prove the greedy is optimal with an exchange argument: why can any optimal set of trades be transformed into the sum of positive differences without losing profit?

Further reading on the technique: Greedy algorithm

Related LeetCode Problems

Practice more problems similar to Best Time to Buy and Sell Stock II.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.