Problem
You are given an integer array
priceswhereprices[i]is the price of NeetCoin on theith day. You may choose a single day to buy one NeetCoin and choose a different day in the future to sell it. Return the maximum profit you can achieve. You may choose to not make any transactions, in which case the profit would be0.
Example 1
Input: prices = [10,1,5,6,7,1]
Output: 6
Buy at prices[1] = 1, sell at prices[4] = 7, profit 7 - 1 = 6.
Example 2
Input: prices = [10,8,7,5,2]
Output: 0
Prices only go down, so no profitable transaction exists.
Constraints
1 <= len(prices) <= 1000 <= prices[i] <= 100
Thinking
- Brute force idea: try every pair
buy < selland keep the bestprices[sell] - prices[buy]. pairs. - Key insight: fix the sell day. The best buy for it is simply the cheapest price seen
so far. So one left-to-right pass keeps a running
min_priceand asks, at every day, “if I sold today, what would I make?” → time, space. - Same idea, other views:
- Two pointers / sliding window:
l= buy day,r= sell day; wheneverprices[r] < prices[l], jumpltor(a new low makes every older buy day worse). - Kadane: the profit of buying on day
iand selling on dayjis the sum of the daily changesprices[k+1] - prices[k]in between, so the answer is the max subarray sum of the daily changes (or 0).
- Two pointers / sliding window:
- Edge cases to remember: one day (no transaction possible → 0); strictly decreasing (→ 0,
never negative); all equal (→ 0); the minimum appears after the maximum (
[7,1]→ 0, you can’t sell before you buy); a new low later on that gives a bigger profit ([3,8,1,9]→ 8); prices of 0.
Solution
Approach A — mine: running minimum, one pass
Complexity: Time · Space
Already optimal in Big-O; it is the sliding window of Approach C with only the buy price kept instead of the buy day. For every day, update the cheapest buy price so far, then check the profit of selling today. Updating buy before computing the profit is fine: if today is the new low, the profit is 0, which never beats max_sell. Two small things to tidy (not speed): the if price - buy > 0 is redundant since max(max_sell, 0) changes nothing, and return on empty input gives None instead of 0 (unreachable here since len(prices) >= 1).
def max_profit_mine(prices: list[int]) -> int:
if not prices:
return # returns None, not 0 (unreachable: len(prices) >= 1)
buy = prices[0]
max_sell = 0
for price in prices:
buy = min(buy, price)
if price - buy > 0: # redundant: max() already ignores profits <= 0
max_sell = max(max_sell, price - buy)
return max_sell
Approach B — brute force, every buy/sell pair
Complexity: Time · Space
Directly the definition. Obviously correct, so the tests use it as the reference on random inputs. Fine at (~5000 pairs), but it doesn’t scale (LeetCode’s own version has up to ).
def max_profit_brute(prices: list[int]) -> int:
best = 0
for buy in range(len(prices)):
for sell in range(buy + 1, len(prices)): # O(n) inner loop for every buy day
best = max(best, prices[sell] - prices[buy])
return best
Approach C — sliding window (two pointers) ✅ best practice
Complexity: Time · Space
The version to remember. The window is [l, r]: l is the buy day, r the sell day. r always moves right; if prices[r] drops below the buy price, the window shrinks to start at r (a new low beats every older buy day), otherwise record the profit of the window. Same logic as A, but the explicit window carries over to the other sliding-window problems (#3, #424, #567).
def max_profit_sliding_window(prices: list[int]) -> int:
l, best = 0, 0
for r in range(1, len(prices)):
if prices[r] < prices[l]: # new low: every later sale is better bought here
l = r
else:
best = max(best, prices[r] - prices[l])
return best
Approach D — Kadane on the daily changes
Complexity: Time · Space
Buying on day i and selling on day j earns sum(prices[k+1] - prices[k] for k in i..j-1), so the answer is the maximum subarray sum of the daily changes. Worth knowing because it links this problem to Maximum Subarray (#53).
def max_profit_kadane(prices: list[int]) -> int:
best = cur = 0
for prev, price in zip(prices, prices[1:]):
cur = max(0, cur + price - prev) # best profit for a sale today; reset if it goes negative
best = max(best, cur)
return best
Approach E — Pythonic: accumulate the running minimum
Complexity: Time · Space (lazy iterators)
accumulate(prices, min) yields the cheapest price up to each day, so the answer is the largest gap between a price and the running min up to it. A one-liner; in an interview write C and mention this as the Pythonic form.
from itertools import accumulate
def max_profit_accumulate(prices: list[int]) -> int:
return max(p - low for p, low in zip(prices, accumulate(prices, min)))
Scratch / Experiments
The constraints cap at 100, too small to show a difference, so the approaches are timed at (LeetCode’s limit) and the brute force at .
Measured (two runs): at , accumulate ~5.3–5.6 ms, mine ~6.1 ms, sliding window ~5.7–6.9 ms (noisy), Kadane ~6.8–7.6 ms. At , brute force ~84–90 ms vs mine ~0.12 ms (~700×, and the gap grows linearly with ).
All four versions are within run-to-run noise of each other, so pick by clarity, not speed. accumulate is consistently a little ahead because its loop runs in C. Kadane is consistently last: it builds prices[1:] and does two max() calls per step. None of this matters at .
rng = random.Random(0)
prices = [rng.randint(0, 10_000) for _ in range(100_000)]
assert max_profit_mine(prices) == max_profit_sliding_window(prices) == max_profit_kadane(prices) == max_profit_accumulate(prices)
%timeit max_profit_mine(prices)
%timeit max_profit_sliding_window(prices)
%timeit max_profit_kadane(prices)
%timeit max_profit_accumulate(prices)
small = prices[:2000]
assert max_profit_brute(small) == max_profit_mine(small)
%timeit -n 1 -r 3 max_profit_brute(small)
%timeit max_profit_mine(small)
Takeaways
- Pattern: “best pair
i < j” → fix the right end and keep the best left end seen so far. Here the best left end is the running minimum, so one pass replaces the pair scan. Write it as a sliding window[l, r]:ralways advances,ljumps torwhen the window stops being worth keeping (a new low). That shape is the template for every sliding-window problem. The same trick shows up as “running max/min + answer at each step” and as Kadane’s algorithm on the differences. - Mistakes I made: none in the algorithm, it’s the optimal / solution. Polish:
- The
if price - buy > 0guard is unnecessary:max_sellstarts at 0, somax(max_sell, price - buy)already ignores non-positive profits. Fewer branches, fewer bugs. returnwith no value returnsNone; if you guard empty input,return 0to keep the return typeint.- Name things for what they hold:
max_sellis really the max profit,buyis the min price so far.
- The
- Related problems: Best Time to Buy and Sell Stock II (#122, unlimited transactions: sum
every positive daily change), III (#123, at most two transactions) and IV (#188, at most
k, DP over states), with Cooldown (#309) and with Transaction Fee (#714) (state-machine DP); Maximum Subarray (#53, the Kadane view of this problem); Longest Substring Without Repeating Characters (#3, the next sliding-window problem).