Skip to content

Resource · Guide or article

Best Time to Buy and Sell Stock

Solves the multiple-transaction version of the stock profit problem three ways, moving from exponential recursion to two single-pass methods. Suits candidates practicing how to talk an interviewer through better and better solutions.

Reviewed

Open the original: Best Time to Buy and Sell Stock (opens the original site in a new tab)

Add to a roadmap

Keep this resource with a roadmap you follow. It appears as your own extra resource; the roadmap's steps don't change and it doesn't count toward your tracked steps.

Source content: English

Say you have an array prices for which the i-th element is the price of a given stock on day i. Find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

PrepKit overview

PrepKit editors wrote and reviewed this overview from the source repository. It is not text from the resource itself.

Suited to
The source does not state a level
Format
Lesson

What it covers

  • Task statement with three worked price arrays and their expected profits
  • Divide and conquer: keep or trade at each day, O(2^n) time and O(n) extra space
  • Peak valley approach: buy at valleys and sell at peaks, O(n) time and O(1) extra space
  • Accumulator approach: add every upward price difference, also O(n) time and O(1) space

How to use it

PrepKit study advice, not a claim made by the source.

Code all three versions, then explain aloud in a couple of minutes why summing every rise gives the same answer as peak valley. Next, try the single-transaction variant, which the page does not cover.

Scope and limitations

Covers only the unlimited-transactions variant. The two charts are LeetCode images, and the code sits in the folder's separate JavaScript files rather than on the page.

Access and format

README on GitHub in trekhleb/javascript-algorithms (MIT), linking three JavaScript solution files. English, free.

Reviewed by PrepKit on Oct 2, 2026. Listing source commit: 85293e3e2b88

Evidence behind this overview
  • src/algorithms/uncategorized/best-time-to-buy-sell-stocks/README.md

Pages that include this

Get the PrepKit newsletter

Optional. You don't need it to use PrepKit.

How we handle your email