1. Cheapest so far
Track the lowest buy price seen to the left.
let minPrice = InfinityTyporithm · easy
Step 1 of 8 · intro card
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.
Track the running minimum buy price.
Profit = price minus running min.
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;
}Connect each part of the code to the concept before you type.
Track the lowest buy price seen to the left.
let minPrice = InfinityA cheaper price becomes the new buy candidate.
if (price < minPrice) {
minPrice = price;
}Otherwise, the profit from selling today may beat the best.
else if (price - minPrice > best) {
best = price - minPrice;
}Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.