Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Best Time to Buy and Sell Stock

LeetCode #121Easy
Track the cheapest day seen so far

Given an array where prices[i] is the price of a stock on day i, maximize your profit by choosing one day to buy and a later day to sell. Return the maximum profit, or 0 if no profit is possible.

Asked atAmazonMetaMicrosoftBloomberg
step 1 / 10
7
1
5
3
6
4
[0][1][2][3][4][5]
Greedy · one pass tracking the minimum
1given prices
2min_so_far ← prices[0]
3max_profit ← 0
4for i ← 1 to n − 1:
5 max_profit = max(max_profit, prices[i] − min_so_far)
6 min_so_far = min(min_so_far, prices[i])
7return max_profit
state
  • n6

line 1prices = [7, 1, 5, 3, 6, 4], one entry per day. We may buy once and sell once on a LATER day. Find the maximum profit. Brute force checks every (buy, sell) pair in O(n²) — but a single greedy pass does it in O(n).