The "Best Time to Buy and Sell Stock interview question" is perhaps the most famous coding challenge in the world. You are given an array of prices where prices[i] is the price of a given stock on day . You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. If no profit can be made, return 0.
This "Best Time to Buy and Sell Stock coding problem" is asked by literally every major tech company, from Google to Apple to Bloomberg. It is the perfect introductory problem to test "Dynamic Programming" and "Array interview pattern" logic. It assesses if a candidate can optimize a search from to by keeping track of a "running minimum."
The solution uses a Single Pass Greedy approach.
min_price to infinity and max_profit to 0.min_price, update min_price.current_price - min_price.max_profit if the current potential profit is higher.
This ensures you always buy at the lowest point seen before the current day.Prices: [7, 1, 5, 3, 6, 4]
min_price = 7.min_price = 1.max_profit = 4.max_profit = 5.min_price to 0 instead of a very large number, which prevents it from ever being updated by the actual prices.This is the "Hello World" of Dynamic Programming. Master this logic before moving on to its more complex variations (Stock II, III, IV). It teaches you the vital skill of "tracking the state" while moving through an array.