{"id":"best-time-to-buy-and-sell-stock","title":"Best Time to Buy and Sell Stock","difficulty":"easy","patterns":["two-pointers"],"primaryConcept":"array-two-pointers-scan","concepts":["array-two-pointers-scan"],"problemForm":"intro","companies":[],"category":"arrays-strings","compareMode":"exact","description":"Given an array `prices` where `prices[i]` is the stock price on day `i`, return the maximum profit you can make by choosing one day to buy and a later day to sell.\n\nRequirements:\n- You may complete at most one transaction.\n- You must buy before you sell.\n- If no profitable transaction exists, return 0.","examples":[{"input":"prices = [7,1,5,3,6,4]","output":"5","explanation":"Buy at price 1 and sell later at price 6 for profit 5."},{"input":"prices = [7,6,4,3,1]","output":"0","explanation":"The price only decreases, so no profitable transaction is possible."},{"input":"prices = [2,4,1]","output":"2","explanation":"Buy at 2 and sell at 4 before the later lower price appears."}],"constraints":[{"id":"1-len-prices-10-5","text":"1 <= len(prices) <= 10^5","check":{"kind":"sizeRange","target":"prices","measure":"arrayLength","min":1,"max":100000}},{"id":"0-prices-i-10-4","text":"0 <= prices[i] <= 10^4","check":{"kind":"valueRange","target":"prices","selector":"arrayItems","min":0,"max":10000}}],"starterCode":"class Solution:\n    def maxProfit(self, prices: list[int]) -> int:\n        # Your code here\n        pass","functionName":"maxProfit","testCases":[{"id":"1","input":{"prices":[7,1,5,3,6,4]},"expected":5,"description":"Canonical buy low then sell later."},{"id":"2","input":{"prices":[7,6,4,3,1]},"expected":0,"description":"No profitable sale."},{"id":"3","input":{"prices":[2,4,1]},"expected":2,"description":"Best sale occurs before the final low."},{"id":"4","input":{"prices":[1]},"expected":0,"description":"Single day cannot form a transaction."},{"id":"5","input":{"prices":[3,2,6,5,0,3]},"expected":4,"description":"Earlier valley produces the best profit."},{"id":"h1","input":{"prices":[1,2]},"expected":1,"description":"Smallest profitable span."},{"id":"h2","input":{"prices":[2,1,2,0,1]},"expected":1,"description":"Multiple valleys with only one-point profit."},{"id":"h3","input":{"prices":[3,3,3]},"expected":0,"description":"Flat prices never profit."},{"id":"h4","input":{"prices":[5,1,3,2,8]},"expected":7,"description":"A later high after an early valley gives the best profit."},{"id":"h5","input":{"prices":[8,6,7,2,9,1]},"expected":7,"description":"The deepest later valley produces the best trade."}],"hints":[{"level":1,"content":"For each possible sell day, what is the best buy price seen before it?","revealPattern":false},{"level":2,"content":"Scan once while tracking the lowest price so far and the best profit so far.","revealPattern":true},{"level":3,"content":"Check the possible sale before lowering the minimum price for future days.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which way of finding the best trade still works on 100,000 days?","decisionPrompt":"Compare how many checks each one makes as the list grows.","approaches":[{"id":"all-pairs","name":"Try every pair of days","summary":"Pair each buy day with every later sell day and keep the largest profit.","decisionReason":"For n days that is about n²/2 pairs, close to five billion at 100,000 days.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["O(n^2) time and O(1) space."],"isOptimal":false},{"id":"one-pass","name":"Carry the cheapest price so far","summary":"Read the prices once, pricing a sale on each day against the cheapest price before it.","decisionReason":"Each day needs one subtraction against a single remembered price, so n days take n steps.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["O(n) time and O(1) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-state","title":"Set up the two numbers","description":"Before any day is read, set the best profit to 0 and the cheapest price so far to infinity.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_and_sentinel_numeric_states","scope":"init-state","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Starting the cheapest price at 0. No price is ever lower than 0, so it never changes and every day looks like pure profit.","Starting the best profit below 0. A list that only falls would then return a loss."],"hint":"The best profit starts at 0, the result of making no trade. The cheapest price starts at infinity, or at the largest value the number type can hold, so that the first real price is lower and takes its place.","semanticSpec":{"intent":"Track the cheapest price seen and best profit found so far.","doneWhen":"Track the cheapest price seen and best profit found so far.","mustProve":["Track the cheapest price seen and best profit found so far."],"mustNotAccept":["Initializing profit to a negative number","Forgetting no profit should return 0"],"proofSnippets":[{"id":"py-stock-init-state","language":"python","code":"def maxProfit(prices: list[int]) -> int:\n    min_price = float(\"inf\")\n    max_profit = 0\n    return max_profit"}],"roles":["minimum price","maximum profit","non-negative baseline"]}},{"id":"scan-prices","title":"Read the prices in order","description":"Go through the days from first to last, one price at a time.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Sorting the prices first. Sorting loses which day came before which, and a sale has to follow its buy."],"hint":"First to last is the order the days happen in, so every price already read belongs to an earlier day.","semanticSpec":{"intent":"Visit each day from left to right so buy-before-sell order is preserved.","doneWhen":"Visit each day from left to right so buy-before-sell order is preserved.","mustProve":["Visit each day from left to right so buy-before-sell order is preserved."],"mustNotAccept":["Sorting prices","Looking ahead without preserving order"],"proofSnippets":[{"id":"py-stock-scan-prices","language":"python","code":"def maxProfit(prices: list[int]) -> int:\n    min_price = float(\"inf\")\n    max_profit = 0\n    for price in prices:\n        return 0\n    return 0"}],"roles":["price sequence","current day","ordered scan"]}},{"id":"update-profit","title":"Price a sale on the current day","description":"Subtract the cheapest price so far from the current price, and keep the result as the best profit if it is larger.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_extremum_from_scan_difference","scope":"update-profit","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Subtracting the other way around, the cheapest price minus the current price.","Replacing the best profit with the current day's sale even when that sale is smaller."],"hint":"The current price is the sale and the cheapest price so far is the buy. The best profit never goes down.","semanticSpec":{"intent":"Treat the current day as a sell day and compare price - min_price with best profit.","doneWhen":"Treat the current day as a sell day and compare price - min_price with best profit.","mustProve":["Treat the current day as a sell day and compare price - min_price with best profit."],"mustNotAccept":["Using future minimum prices","Subtracting in the wrong direction"],"proofSnippets":[{"id":"py-stock-update-profit","language":"python","code":"def maxProfit(prices: list[int]) -> int:\n    min_price = float(\"inf\")\n    max_profit = 0\n    for price in prices:\n        max_profit = max(max_profit, price - min_price)\n        return 0\n    return 0"}],"roles":["current sell price","minimum prior buy price","best profit"]}},{"id":"update-min","title":"Keep the cheapest price up to date","description":"If the current price is lower than the cheapest price so far, it becomes the new cheapest.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_running_extremum_from_scan_value","scope":"update-min","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Setting the best profit back to 0 when a lower price arrives. A profit already found still counts.","Leaving the cheapest price at its starting value. Every sale is then measured against infinity, and no profit is ever found."],"hint":"A lower price cannot change a sale that already happened. It is a better buy for every day still to come.","semanticSpec":{"intent":"After considering the current price, keep it if it is the cheapest seen so far.","doneWhen":"After considering the current price, keep it if it is the cheapest seen so far.","mustProve":["After considering the current price, keep it if it is the cheapest seen so far."],"mustNotAccept":["Never updating the valley","Resetting profit when a new valley appears"],"proofSnippets":[{"id":"py-stock-update-min","language":"python","code":"def maxProfit(prices: list[int]) -> int:\n    min_price = float(\"inf\")\n    max_profit = 0\n    for price in prices:\n        max_profit = max(max_profit, price - min_price)\n        min_price = min(min_price, price)\n        return 0\n    return 0"}],"roles":["current price","minimum price","future sell day"]}},{"id":"return-profit","title":"Return the best profit","description":"After the last day has been read, return the best profit so far.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_extremum_numeric_state","scope":"return-profit","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Returning the last day's sale, which is only one of the candidates.","Returning from inside the loop, before every day has been read."],"hint":"If no sale ever made money it is still 0, which is the required result for that case.","semanticSpec":{"intent":"Return the tracked best profit after evaluating every sell day.","doneWhen":"This step is done when the function returns the max profit state after the ordered price scan completes.","shouldFailWhen":"This step should fail if the code returns the minimum price, current day profit only, or a negative value for decreasing prices.","roles":["best profit","terminal return","price scan"],"mustProve":["The best-profit state is updated during the scan.","The function returns the best-profit state after the scan."],"mustNotAccept":["Returning min_price.","Returning price - min_price from only the final day.","Returning a negative value when no profitable trade exists."],"equivalentVariants":["Return max_profit after the loop.","Return an equivalent non-negative best-profit accumulator."],"proofSnippets":[{"id":"py-stock-return-profit","language":"python","code":"def maxProfit(prices: list[int]) -> int:\n    min_price = float(\"inf\")\n    max_profit = 0\n    for price in prices:\n        max_profit = max(max_profit, price - min_price)\n        min_price = min(min_price, price)\n    return max_profit"}]}}],"version":2,"progressRevision":"best-time-to-buy-and-sell-stock-2026-11-20-cheapest-price-so-far","slides":[{"id":"read-the-signal","kind":"info","title":"Buy on one day, sell on a later day","workspacePanel":"problem","body":["A stock has one price per day, listed in order. The first day is day 0. You may buy once and sell once, and the sale has to come on a later day than the buy. That buy and its sale together are one trade.","Return the largest profit one trade can make. The profit is the sell price minus the buy price. If no trade makes money, the answer is $0."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"six-days","state":{"nums":[7,1,5,3,6,4],"labels":{"nums":"prices"}}}]}},{"id":"best-trade","kind":"case-probe","title":"What is the most profit one trade can make on these six days?","workspacePanel":"visualizer","options":[{"id":"five","label":"$5, buying at $1 and selling at $6","rationale":"Buy at $1 on day 1 and sell at $6 on day 4: $6 - $1 = $5. No other trade earns more.","isCorrect":true},{"id":"six","label":"$6, buying at $1 and selling at $7","rationale":"The $7 is on day 0 and the $1 is on day 1. That sale would come before the buy, so it is not a trade you can make.","isCorrect":false},{"id":"four","label":"$4, buying at $1 and selling at $5","rationale":"That trade is allowed, and it earns $4. Another trade on these six days earns more.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"six-days","state":{"nums":[7,1,5,3,6,4],"labels":{"nums":"prices"}}}]}},{"id":"brute-force","kind":"code-trace","title":"Try every buy day with every later sell day","workspacePanel":"trace","body":["One way for a program to find that $5 is to try every pair of days. The outer loop picks a buy day. The inner loop tries each later day as the sale and keeps the largest profit in `best`."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"best = 0\nfor buy in range(len(prices)):\n    for sell in range(buy + 1, len(prices)):\n        profit = prices[sell] - prices[buy]\n        if profit > best:\n            best = profit\nreturn best","steps":[{"id":"first-pair","title":"Buy at $7, sell at $1","codeLine":4,"summary":"$1 - $7 = -$6. A loss does not beat `best`, so it stays 0.","state":{"nums":[7,1,5,3,6,4],"i":0,"j":1,"profit":-6,"best":0,"pairs checked":1,"labels":{"nums":"prices","i":"buy","j":"sell"}}},{"id":"day-zero-done","title":"Buying at $7 never makes money","codeLine":4,"summary":"Every later price is below $7, so all five sales lose money.","state":{"nums":[7,1,5,3,6,4],"i":0,"j":5,"profit":-3,"best":0,"pairs checked":5,"labels":{"nums":"prices","i":"buy","j":"sell"}}},{"id":"first-profit","title":"Buy at $1, sell at $5","codeLine":6,"summary":"$5 - $1 = $4 beats 0, so `best` becomes 4.","state":{"nums":[7,1,5,3,6,4],"i":1,"j":2,"profit":4,"best":4,"pairs checked":6,"labels":{"nums":"prices","i":"buy","j":"sell"}}},{"id":"best-pair","title":"Buy at $1, sell at $6","codeLine":6,"summary":"$6 - $1 = $5 beats 4, so `best` becomes 5.","state":{"nums":[7,1,5,3,6,4],"i":1,"j":4,"profit":5,"best":5,"pairs checked":8,"labels":{"nums":"prices","i":"buy","j":"sell"}}},{"id":"all-pairs-done","title":"The remaining pairs find nothing better","codeLine":7,"summary":"The seven pairs still to check earn at most $3. Six days took 15 pairs in all, and the function returns $5.","state":{"nums":[7,1,5,3,6,4],"profit":-2,"best":5,"pairs checked":15,"labels":{"nums":"prices"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let best = 0;\nfor (let buy = 0; buy < prices.length; buy++) {\n    for (let sell = (buy + 1); sell < prices.length; sell++) {\n        const profit = prices[sell] - prices[buy];\n        if (profit > best) {\n            best = profit;\n        }\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let best = 0;\nfor (let buy = 0; buy < prices.length; buy++) {\n    for (let sell = (buy + 1); sell < prices.length; sell++) {\n        const profit = prices[sell] - prices[buy];\n        if (profit > best) {\n            best = profit;\n        }\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int best = 0;\nfor (int buy = 0; buy < prices.size(); buy++) {\n    for (int sell = (buy + 1); sell < prices.size(); sell++) {\n        int profit = prices.get(sell) - prices.get(buy);\n        if (profit > best) {\n            best = profit;\n        }\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int best = 0;\nfor (int buy = 0; buy < prices.Count; buy++) {\n    for (int sell = buy + 1; sell < prices.Count; sell++) {\n        int profit = prices[sell] - prices[buy];\n        if (profit > best) {\n            best = profit;\n        }\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int best = 0;\nfor (int buy = 0; buy < prices.size(); buy++) {\n    for (int sell = (buy + 1); sell < prices.size(); sell++) {\n        int profit = prices[sell] - prices[buy];\n        if (profit > best) {\n            best = profit;\n        }\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}}}}},{"id":"repeated-work","kind":"case-probe","title":"Six days took 15 pairs. About how many would 1,000 days take?","workspacePanel":"trace","options":[{"id":"half-million","label":"About 500,000","rationale":"Day 0 pairs with 999 later days, day 1 with 998, and so on down to 1. Those add up to 499,500. The longest list this problem allows has 100,000 days, which is about five billion pairs.","isCorrect":true},{"id":"straight-line","label":"About 2,500","rationale":"That scales 15 pairs for six days up in a straight line. Each added day pairs with every day before it, so the count grows faster than the number of days.","isCorrect":false},{"id":"one-per-day","label":"About 1,000","rationale":"That would be one check per day. Each day is tried against every later day, which is far more pairs than days.","isCorrect":false}]},{"id":"best-buy","kind":"case-probe","title":"Let's say you sell on day 4, at $6. Which earlier day is the best one to buy on?","workspacePanel":"visualizer","options":[{"id":"cheapest-earlier","label":"Day 1, at $1","rationale":"$6 - $1 = $5. With the sale fixed at $6, the lowest earlier price leaves the most profit.","isCorrect":true},{"id":"day-before","label":"Day 3, at $3","rationale":"Buying the day before earns $6 - $3 = $3. Another earlier day costs less, so it earns more.","isCorrect":false},{"id":"first-day","label":"Day 0, at $7","rationale":"$7 is more than the $6 sale price, so this trade loses $1.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sell-day-4","state":{"nums":[7,1,5,3,6,4],"i":4,"labels":{"nums":"prices","i":"sell"}}}]}},{"id":"cheapest-so-far","kind":"case-probe","title":"Suppose the sale is on day 5 instead, at $4. What do you need to know about days 0 to 4?","workspacePanel":"visualizer","options":[{"id":"lowest-only","label":"Only the lowest of the five prices","rationale":"The best buy is the $1 on day 1, and $4 - $1 = $3. None of the other four prices does better.","isCorrect":true},{"id":"all-five","label":"All five prices","rationale":"Trying day 5 against each earlier day is the pair loop again. Most of those comparisons cannot be the best one.","isCorrect":false},{"id":"day-before","label":"Only the price on day 4","rationale":"The day before is $6, and an earlier day is cheaper than that. The best buy can be many days back.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sell-day-5","state":{"nums":[7,1,5,3,6,4],"i":5,"labels":{"nums":"prices","i":"sell"}}}]}},{"id":"dry-run-setup","kind":"info","title":"One pass that carries two numbers","workspacePanel":"visualizer","body":["Reading the prices once, from the first day to the last, is called a pass. The lowest price so far can be kept up to date during a pass, one day at a time.","So the pass carries two numbers. The first is the cheapest price so far. On any day after the first, today's price minus the cheapest earlier price is the best sale that day can make.","The second is the best profit so far. It works the way `best` did when trying every pair.","Before day 0, no price has been seen. The best profit starts at $0, and the cheapest price starts at infinity."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"before-any-day","state":{"nums":[7,1,5,3,6,4],"cheapest so far":"Infinity","best profit":0,"labels":{"nums":"prices"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Six days, one pass","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"before-day-0","state":{"nums":[7,1,5,3,6,4],"i":0,"cheapest so far":"Infinity","best profit":0,"labels":{"nums":"prices","i":"today"}}},{"id":"before-day-1","state":{"nums":[7,1,5,3,6,4],"i":1,"j":0,"cheapest so far":7,"best profit":0,"labels":{"nums":"prices","i":"today","j":"cheapest"}}},{"id":"before-day-2","state":{"nums":[7,1,5,3,6,4],"i":2,"j":1,"cheapest so far":1,"best profit":0,"labels":{"nums":"prices","i":"today","j":"cheapest"}}},{"id":"before-day-3","state":{"nums":[7,1,5,3,6,4],"i":3,"j":1,"cheapest so far":1,"best profit":4,"labels":{"nums":"prices","i":"today","j":"cheapest"}}},{"id":"before-day-4","state":{"nums":[7,1,5,3,6,4],"i":4,"j":1,"cheapest so far":1,"best profit":4,"labels":{"nums":"prices","i":"today","j":"cheapest"}}},{"id":"before-day-5","state":{"nums":[7,1,5,3,6,4],"i":5,"j":1,"cheapest so far":1,"best profit":5,"labels":{"nums":"prices","i":"today","j":"cheapest"}}},{"id":"pass-finished","state":{"nums":[7,1,5,3,6,4],"j":1,"cheapest so far":1,"best profit":5,"returns":5,"labels":{"nums":"prices","j":"cheapest"}}}]},"beats":[{"id":"day-0","title":"Day 0's price is $7. What do the two numbers become?","options":[{"id":"seven-zero","label":"Cheapest $7, best profit $0","rationale":"$7 is lower than infinity, so it becomes the cheapest price. There is no earlier day to buy on, so the best profit stays $0.","isCorrect":true},{"id":"seven-seven","label":"Cheapest $7, best profit $7","rationale":"A profit needs a buy on an earlier day and a sale today. Day 0 has no earlier day, so nothing has been earned.","isCorrect":false},{"id":"unchanged","label":"Cheapest infinity, best profit $0","rationale":"$7 is a real price and it is lower than infinity, so the cheapest price so far has to become $7.","isCorrect":false}]},{"id":"day-1","title":"Day 1's price falls to $1. What do the two numbers become?","options":[{"id":"one-zero","label":"Cheapest $1, best profit $0","rationale":"Selling at $1 after buying at $7 would lose $6, which does not beat $0. The $1 is lower than $7, so it becomes the cheapest price.","isCorrect":true},{"id":"one-negative","label":"Cheapest $1, best profit -$6","rationale":"$1 - $7 = -$6, a loss. Making no trade earns $0, which is better, so the best profit stays $0.","isCorrect":false},{"id":"seven-zero","label":"Cheapest $7, best profit $0","rationale":"The best profit does stay $0, but $1 is lower than $7, so it is the better buy for every later day.","isCorrect":false}]},{"id":"day-2","title":"Day 2's price rises to $5. What is the best profit now?","options":[{"id":"four","label":"$4, from $5 - $1","rationale":"A sale today earns $5 minus the cheapest price so far, which is $1. $4 beats $0, so it becomes the best profit.","isCorrect":true},{"id":"zero","label":"$0, since $5 - $7 is a loss","rationale":"The $7 on day 0 is no longer the cheapest price, so a sale today is measured against a lower one.","isCorrect":false},{"id":"five","label":"$5, today's price","rationale":"A profit is the sale minus the buy. $5 is only the sale price, with nothing taken off for the buy.","isCorrect":false}]},{"id":"day-3","title":"Day 3's price is $3. What happens to the two numbers?","options":[{"id":"neither","label":"Neither changes","rationale":"A sale today earns $3 - $1 = $2, which does not beat $4. And $3 is not lower than $1, so the cheapest price stays where it is.","isCorrect":true},{"id":"profit-drops","label":"The best profit drops to $2","rationale":"$2 is what a sale today would earn. The best profit keeps the largest profit found so far, and that is still $4.","isCorrect":false},{"id":"cheapest-moves","label":"The cheapest price becomes $3","rationale":"$3 is lower than yesterday's $5, but the cheapest price so far is the $1 on day 1.","isCorrect":false}]},{"id":"day-4","title":"Day 4's price is $6. What is the best profit now?","options":[{"id":"five","label":"$5, from $6 - $1","rationale":"A sale today is measured against the cheapest price so far, the $1 on day 1. $5 beats $4, so it becomes the best profit.","isCorrect":true},{"id":"three","label":"$3, from $6 - $3","rationale":"That buys on day 3, the day before, at $3. The cheapest price so far is lower, the $1 on day 1.","isCorrect":false},{"id":"four","label":"$4, unchanged","rationale":"A sale today, measured against the cheapest price so far, earns more than $4.","isCorrect":false}]},{"id":"day-5","title":"Day 5's price is $4, the last one. What does the function return?","options":[{"id":"best-profit","label":"$5, the best profit so far","rationale":"A sale today earns $4 - $1 = $3, which does not beat $5. Every day has now been tried as the sale, so the best profit is the answer.","isCorrect":true},{"id":"last-sale","label":"$3, the sale on the last day","rationale":"$3 is only what a sale today would earn. The best profit keeps the largest profit from any day.","isCorrect":false},{"id":"cheapest-price","label":"$1, the cheapest price","rationale":"$1 is the price the best trade bought at. The function returns a profit, which is a sale minus a buy.","isCorrect":false}]}]},{"id":"edge-case-intro","kind":"info","title":"The pass found $5 on these six days. Next, three other lists.","workspacePanel":"visualizer","body":["In these six days, the cheapest price came early and the best sale came after it. The next three lists are not like that.","In the first, the lowest price comes near the end. In the second, the price falls every day. The third has only one day.","Does the same pass still give the right answer for each one?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"six-days-finished","state":{"nums":[7,1,5,3,6,4],"j":1,"cheapest so far":1,"best profit":5,"labels":{"nums":"prices","j":"cheapest"}}}]}},{"id":"late-low-edge","kind":"case-probe","title":"In the first list, the lowest price comes on day 4. What does the function return?","workspacePanel":"visualizer","options":[{"id":"four","label":"$4, buying at $2 and selling at $6","rationale":"That sale is on day 2, and the best profit keeps its $4. After the $0 arrives, the only sale left is $3 - $0 = $3, which does not beat $4.","isCorrect":true},{"id":"three","label":"$3, buying at $0 and selling at $3","rationale":"That is the best trade that uses the lowest price, and it earns $3. A trade made before the $0 arrived earned more.","isCorrect":false},{"id":"six","label":"$6, buying at $0 and selling at $6","rationale":"The $6 is on day 2 and the $0 is on day 4. That sale would come before the buy.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"late-low","state":{"nums":[3,2,6,5,0,3],"labels":{"nums":"prices"}}}]}},{"id":"only-falls-edge","kind":"case-probe","title":"In the second list, the price falls every day. What does the function return?","workspacePanel":"visualizer","options":[{"id":"zero","label":"$0, from making no trade","rationale":"Every day's price is below the cheapest price before it, so every sale would be a loss. The best profit never moves from its starting $0.","isCorrect":true},{"id":"smallest-loss","label":"-$1, the smallest loss","rationale":"Selling one day after buying at $7 or at $4 loses $1, and no trade does better. Making no trade earns $0, and the best profit started there.","isCorrect":false},{"id":"six","label":"$6, from $7 - $1","rationale":"The $7 is the first price and the $1 is the last. Buying at $1 and selling at $7 would need the days in the other order.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"only-falls","state":{"nums":[7,6,4,3,1],"labels":{"nums":"prices"}}}]}},{"id":"single-day-edge","kind":"case-probe","title":"The last list has only one day. What does the function return?","workspacePanel":"visualizer","options":[{"id":"zero","label":"$0, with no trade made","rationale":"$5 replaces infinity as the cheapest price, and there is no earlier day to have bought on. The best profit is still $0 when the pass ends.","isCorrect":true},{"id":"five","label":"$5, the only price","rationale":"$5 is the price on that day. A profit needs a buy and a later sale, and one day cannot hold both.","isCorrect":false},{"id":"fails","label":"Nothing, because the function fails","rationale":"The pass reads the one price and finishes normally. No step in it reads a second day.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-day","state":{"nums":[5],"labels":{"nums":"prices"}}}]}},{"id":"ready-to-code","kind":"info","title":"You have the whole plan. Now write it as a function.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["The function reads the prices once, from the first day to the last. It keeps two numbers: the cheapest price so far, which starts at infinity, and the best profit so far, which starts at $0.","On each day, it works out what selling today would earn, which is today's price minus the cheapest price so far. If that beats the best profit, it becomes the new best profit.","Then, if today's price is lower than the cheapest price so far, it becomes the new cheapest price.","After the last day, the function returns the best profit. If no trade made money, that is still $0."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"starting-values","state":{"nums":[7,1,5,3,6,4],"cheapest so far":"Infinity","best profit":0,"labels":{"nums":"prices"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Best profit in one pass","workspacePanel":"code","checkpoints":[{"id":"init-state","title":"Set up the two numbers","description":"Before any day is read, set the best profit to 0 and the cheapest price so far to infinity.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_and_sentinel_numeric_states","scope":"init-state","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Starting the cheapest price at 0. No price is ever lower than 0, so it never changes and every day looks like pure profit.","Starting the best profit below 0. A list that only falls would then return a loss."],"hint":"The best profit starts at 0, the result of making no trade. The cheapest price starts at infinity, or at the largest value the number type can hold, so that the first real price is lower and takes its place.","semanticSpec":{"intent":"Track the cheapest price seen and best profit found so far.","doneWhen":"Track the cheapest price seen and best profit found so far.","mustProve":["Track the cheapest price seen and best profit found so far."],"mustNotAccept":["Initializing profit to a negative number","Forgetting no profit should return 0"],"proofSnippets":[{"id":"py-stock-init-state","language":"python","code":"def maxProfit(prices: list[int]) -> int:\n    min_price = float(\"inf\")\n    max_profit = 0\n    return max_profit"}],"roles":["minimum price","maximum profit","non-negative baseline"]}},{"id":"scan-prices","title":"Read the prices in order","description":"Go through the days from first to last, one price at a time.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Sorting the prices first. Sorting loses which day came before which, and a sale has to follow its buy."],"hint":"First to last is the order the days happen in, so every price already read belongs to an earlier day.","semanticSpec":{"intent":"Visit each day from left to right so buy-before-sell order is preserved.","doneWhen":"Visit each day from left to right so buy-before-sell order is preserved.","mustProve":["Visit each day from left to right so buy-before-sell order is preserved."],"mustNotAccept":["Sorting prices","Looking ahead without preserving order"],"proofSnippets":[{"id":"py-stock-scan-prices","language":"python","code":"def maxProfit(prices: list[int]) -> int:\n    min_price = float(\"inf\")\n    max_profit = 0\n    for price in prices:\n        return 0\n    return 0"}],"roles":["price sequence","current day","ordered scan"]}},{"id":"update-profit","title":"Price a sale on the current day","description":"Subtract the cheapest price so far from the current price, and keep the result as the best profit if it is larger.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_extremum_from_scan_difference","scope":"update-profit","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Subtracting the other way around, the cheapest price minus the current price.","Replacing the best profit with the current day's sale even when that sale is smaller."],"hint":"The current price is the sale and the cheapest price so far is the buy. The best profit never goes down.","semanticSpec":{"intent":"Treat the current day as a sell day and compare price - min_price with best profit.","doneWhen":"Treat the current day as a sell day and compare price - min_price with best profit.","mustProve":["Treat the current day as a sell day and compare price - min_price with best profit."],"mustNotAccept":["Using future minimum prices","Subtracting in the wrong direction"],"proofSnippets":[{"id":"py-stock-update-profit","language":"python","code":"def maxProfit(prices: list[int]) -> int:\n    min_price = float(\"inf\")\n    max_profit = 0\n    for price in prices:\n        max_profit = max(max_profit, price - min_price)\n        return 0\n    return 0"}],"roles":["current sell price","minimum prior buy price","best profit"]}},{"id":"update-min","title":"Keep the cheapest price up to date","description":"If the current price is lower than the cheapest price so far, it becomes the new cheapest.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_running_extremum_from_scan_value","scope":"update-min","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Setting the best profit back to 0 when a lower price arrives. A profit already found still counts.","Leaving the cheapest price at its starting value. Every sale is then measured against infinity, and no profit is ever found."],"hint":"A lower price cannot change a sale that already happened. It is a better buy for every day still to come.","semanticSpec":{"intent":"After considering the current price, keep it if it is the cheapest seen so far.","doneWhen":"After considering the current price, keep it if it is the cheapest seen so far.","mustProve":["After considering the current price, keep it if it is the cheapest seen so far."],"mustNotAccept":["Never updating the valley","Resetting profit when a new valley appears"],"proofSnippets":[{"id":"py-stock-update-min","language":"python","code":"def maxProfit(prices: list[int]) -> int:\n    min_price = float(\"inf\")\n    max_profit = 0\n    for price in prices:\n        max_profit = max(max_profit, price - min_price)\n        min_price = min(min_price, price)\n        return 0\n    return 0"}],"roles":["current price","minimum price","future sell day"]}},{"id":"return-profit","title":"Return the best profit","description":"After the last day has been read, return the best profit so far.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_extremum_numeric_state","scope":"return-profit","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Returning the last day's sale, which is only one of the candidates.","Returning from inside the loop, before every day has been read."],"hint":"If no sale ever made money it is still 0, which is the required result for that case.","semanticSpec":{"intent":"Return the tracked best profit after evaluating every sell day.","doneWhen":"This step is done when the function returns the max profit state after the ordered price scan completes.","shouldFailWhen":"This step should fail if the code returns the minimum price, current day profit only, or a negative value for decreasing prices.","roles":["best profit","terminal return","price scan"],"mustProve":["The best-profit state is updated during the scan.","The function returns the best-profit state after the scan."],"mustNotAccept":["Returning min_price.","Returning price - min_price from only the final day.","Returning a negative value when no profitable trade exists."],"equivalentVariants":["Return max_profit after the loop.","Return an equivalent non-negative best-profit accumulator."],"proofSnippets":[{"id":"py-stock-return-profit","language":"python","code":"def maxProfit(prices: list[int]) -> int:\n    min_price = float(\"inf\")\n    max_profit = 0\n    for price in prices:\n        max_profit = max(max_profit, price - min_price)\n        min_price = min(min_price, price)\n    return max_profit"}]}}]},{"id":"complete","kind":"complete","title":"One pass finds the best trade","workspacePanel":"code","takeaways":[{"title":"A sale only needs the cheapest price before it","body":"With the sale price fixed, the profit is largest when the buy price is smallest, so one remembered price stands in for every earlier day."},{"title":"The best profit is kept apart from the cheapest price","body":"On the list that reached $0 on day 4, the answer was still the $4 earned two days earlier. A lower price only matters to the days after it."},{"title":"The starting values cover falling prices and a single day","body":"A best profit of $0 is the result of making no trade, and infinity lets the first price become the cheapest with no special rule."},{"title":"O(n) time and O(1) space","body":"Each of the n prices is read once, with one subtraction and two comparisons. Only two numbers are stored, however long the list is. Trying every pair needed about n²/2 checks."}]}],"slidesOrigin":"authored"},"syntheticTestConfig":{"inputShape":"array","primaryParam":"prices","sizeMetric":"length","constraints":["non-negative"],"valueRange":{"min":0,"max":10000}},"executionStyle":"solution-method"}
