Example 1
- Input
- prices = [7,1,5,3,6,4]
- Output
- 5
Buying on day 2 (index 1) at price 1 and selling on day 5 (index 4) at price 6 gives profit 6 - 1 = 5. The earlier 7 cannot be a sale after buying at 1.
Given an array prices where prices[i] is the price of one stock on day i, choose one day to buy and a later day to sell so that the profit is as large as possible. Return that maximum profit, or 0 when no profitable trade exists.
You are given an array prices where prices[i] is the price of a given stock on day i.
Choose a single day to buy one stock and a different, later day to sell it, maximising prices[sell] - prices[buy]. Return that maximum profit, or 0 when no pair of days yields a profit.
1 <= prices.length <= 10^50 <= prices[i] <= 10^4Buying on day 2 (index 1) at price 1 and selling on day 5 (index 4) at price 6 gives profit 6 - 1 = 5. The earlier 7 cannot be a sale after buying at 1.
Every later price is lower than every earlier one, so no trade earns money and the answer is 0.
There is no later selling day, so no transaction is possible. Return the no-trade profit 0.
The only legal trade loses 8. Subtracting the global minimum from the global maximum would incorrectly give 8, because it would sell before buying.
Buy at 2 and sell at the next 5 for profit 3. The later minimum 1 offers only a later sale at 2, for profit 1; finding a new minimum does not reset the best completed profit.
Imagine checking each day as a possible selling day while remembering the cheapest earlier price. For a fixed sale price, paying less earlier can only improve the profit, so other earlier buy prices can be forgotten. In [7, 1, 5, 3, 6, 4], after seeing 1, the sale prices 5, 3, 6, and 4 offer profits 4, 2, 5, and 3. Keep the largest, 5. A new low helps future sales, but must not erase a better completed trade. The initial answer 0 represents choosing no trade.
Reveal Brute Force: intuition, complexity, and code
i is best paired with the cheapest price among the days before i, so what single value is worth carrying forward?[7, 6, 4, 3, 1], where the minimum keeps dropping and the answer stays 0.[5], where no sale is possible and the answer is 0.[4, 4, 4] have legal trades but no gain, so return 0.[9, 1] returns 0, not 8; order matters.[2, 5, 1, 2] returns 3; keep the earlier best profit while updating the buy candidate.[0, 10000] return 10000; [10000, 0] returns 0.[1, 3, 2, 5] return 4 for one trade; summing separate gains would solve a different multiple-transaction problem.n = 10^5.0.[2, 5, 1, 2] demonstrates.When each position pairs with the best value before it, one forward scan carrying that best-so-far state replaces a quadratic pair search.