03. Best Time to Buy and Sell Stock
Given an array prices where prices[i] is the stock price on day i, return the maximum profit you can achieve from a single transaction.
How It Works & Algorithmic Design
This uses a Single-Pass Greedy Running Minimum strategy:
- Variables: Track
minPrice = InfinityandmaxProfit = 0. - Iteration: Loop through each stock price in
prices:- If the current price is lower than
minPrice, updateminPrice = price. - Otherwise, calculate potential profit:
price - minPrice. If this profit exceedsmaxProfit, updatemaxProfit.
- If the current price is lower than
- Return: Return
maxProfitafter scanning all prices.
Why This Approach Works Best
Checking every pair of buying/selling days with nested loops takes $O(n^2)$ time. Tracking the lowest price seen so far allows maximum profit calculation in $O(n)$ time and $O(1)$ space.
Example Walkthrough
prices = [7, 1, 5, 3, 6, 4]
Daily stock prices.
7 (min=7) -> 1 (min=1) -> 5 (profit=4) -> 3 -> 6 (profit=5, max=5) -> 4
Tracks minPrice and maxProfit concurrently.
5
Buy on day 2 (price=1), sell on day 5 (price=6).
Answer: Maximum stock profit calculation
function maxProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (const price of prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
}Track the minimum price seen so far and update profit whenever a higher selling price occurs.
Stock must be bought before it can be sold (left-to-right order dependency).
Maintain running minimum price to evaluate maximum potential gain.
Single pass achieves $O(n)$ time and $O(1)$ space.