You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy and a different day in the future to sell. Return the maximum profit you can achieve. If no profit is possible, return 0.
prices = [7,1,5,3,6,4]5For any selling day i, the optimal buy day is the minimum price in [0..i-1]. We track the running minimum — no re-scan needed. At each step, profit = todayPrice − lowestSeen. If this beats maxProfit, update it. A decreasing sequence yields profit 0 (we never sell below buy).
Buying at the lowest price overall does not always work, because the selling day must come after it. And checking every pair of days is O(n²).
Walk through the days once, and remember the cheapest price so far. On each day, imagine selling today: the profit is today minus the cheapest so far. Keep the best profit seen.
Keep the cheapest price so far, and ask what selling today would earn. The order of days matters, so one left to right pass handles it.
Run the animation above on your own input, or watch the 1:20 video explanation of Best Time to Buy and Sell Stock with a dry run and Java code.