Typorithm · easy

Best Time to Buy & Sell Stock

best-time-to-buy-sell-stocksliding-windowone-passrunning-minexpanding
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Best Time to Buy & Sell Stock

0%

Sliding Window

Sweep once, keeping the cheapest price so far and the best profit achievable by selling at the current day.

You must buy before you sell, so the window's left edge is the cheapest day seen so far.

Each day, either it is a new minimum buy price or a candidate sell day.

The best profit is the largest gap between the running minimum and the current price.

01

Track the running minimum buy price.

02

Profit = price minus running min.

03

Keep the maximum profit seen.

function maxProfit(prices) {
  let minPrice = Infinity;
  let best = 0;

  for (const price of prices) {
    if (price < minPrice) {
      minPrice = price;
    } else if (price - minPrice > best) {
      best = price - minPrice;
    }
  }

  return best;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Cheapest so far

Track the lowest buy price seen to the left.

let minPrice = Infinity

2. New low

A cheaper price becomes the new buy candidate.

if (price < minPrice) {
      minPrice = price;
    }

3. Best sell

Otherwise, the profit from selling today may beat the best.

else if (price - minPrice > best) {
      best = price - minPrice;
    }

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Best Time to Buy & Sell Stock: Lesson & Practice · Typorithm | ApplyDjinn