Best Time to Buy and Sell Stock in Python: One-Pass Greedy Solution

Tags:

Choose one buy day and a later sell day to maximize profit; return zero if no profitable trade exists.

The best trade respects chronological order: 6 − 1 = 5.

Difficulty: Easy · Pattern: Greedy / prefix minimum · Prerequisites: arrays and loops. Assume nonnegative integer prices; an empty input returns zero. Only one transaction is allowed.

Example

[7,1,5,3,6,4] gives 5: buy at 1 and sell at 6.

Pattern recognition and hints

Track the cheapest price seen so far, rather than comparing every pair.

Hint 1: Fix the selling day. Hint 2: Which earlier price would maximize the difference? Hint 3: Can that minimum be maintained without scanning the prefix again?

Brute force

def brute(prices):
return max([0] + [prices[j]-prices[i]
for i in range(len(prices))
for j in range(i+1,len(prices))])

Optimized or iterative approach

Track the cheapest price seen so far, rather than comparing every pair.

def max_profit(prices):
low = float(“inf”)
best = 0
for price in prices:
low = min(low, price)
best = max(best, price – low)
return best

Step-by-step walkthrough

Prices 7,1,5,3,6,4 produce running minima 7,1,1,1,1,1 and best profits 0,0,4,4,5,5.

DayPriceMinimumBest profit177021103514431456156415

Pseudocode: initialize minimum to infinity and profit to zero. For each price, update the minimum, then maximize profit with the current price minus that minimum. Return profit. A same-day difference is zero and cannot create an invalid positive trade.

Correctness argument

At each day the minimum prefix price gives the largest possible profit ending that day. Taking the maximum over all days covers every feasible trade; zero covers no trade.

Complexity analysis

Brute force O(n²) time and O(n²) space for the list shown; optimized O(n) time and O(1) space.

Edge cases

Descending prices, one price, equal prices, and a late minimum.

Interview follow-ups

Why not subtract the global minimum from the global maximum? The maximum may occur before the minimum. Can we make multiple trades? That is a different problem.

Practice and revision

Original problem · DSA Roadmap

Common mistakes and interview questions

Why is a global minimum insufficient? A later minimum cannot be used to buy before an earlier maximum. Why initialize profit to zero? A losing transaction is optional. Can we return the actual days? Track the minimum index and save the pair whenever profit strictly improves. Can we process a stream? Yes, the two running values are sufficient. What changes with transaction fees or cooldowns? Those variants require different state transitions; this invariant alone is not enough.

Practice variations and quick revision

Try returning the buy and sell indices, allowing unlimited transactions, or imposing a transaction fee. For [7,6,4,3,1], expect zero; for [2,4,1], expect two; for [3,3], expect zero. Remember: scan once, maintain the cheapest prefix price, and update the best legal profit. Explain the chronological constraint before writing code.

Categories

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *