{"id":10594,"date":"2026-11-29T08:32:34","date_gmt":"2026-11-29T08:32:34","guid":{"rendered":"https:\/\/cybersecurityinfocus.com\/?p=10594"},"modified":"2026-11-29T08:32:34","modified_gmt":"2026-11-29T08:32:34","slug":"best-time-to-buy-and-sell-stock-in-python-one-pass-greedy-solution","status":"publish","type":"post","link":"https:\/\/cybersecurityinfocus.com\/?p=10594","title":{"rendered":"Best Time to Buy and Sell Stock in Python: One-Pass Greedy Solution"},"content":{"rendered":"<p class=\"wp-block-paragraph\">Choose one buy day and a later sell day to maximize profit; return zero if no profitable trade exists.<\/p>\n<p>The best trade respects chronological order: 6 \u2212 1 = 5.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Difficulty:<\/strong> Easy \u00b7 <strong>Pattern:<\/strong> Greedy \/ prefix minimum \u00b7 <strong>Prerequisites:<\/strong> arrays and loops. Assume nonnegative integer prices; an empty input returns zero. Only one transaction is allowed.<\/p>\n<h2 class=\"wp-block-heading\">Example<\/h2>\n<p class=\"wp-block-paragraph\">[7,1,5,3,6,4] gives 5: buy at 1 and sell at 6.<\/p>\n<h2 class=\"wp-block-heading\">Pattern recognition and hints<\/h2>\n<p class=\"wp-block-paragraph\">Track the cheapest price seen so far, rather than comparing every pair.<\/p>\n<p class=\"wp-block-paragraph\">Hint 1: Fix the <a href=\"https:\/\/programesecure.com\/selling-globally-from-india\/\">selling<\/a> day. Hint 2: Which earlier price would maximize the difference? Hint 3: Can that minimum be maintained without scanning the prefix again?<\/p>\n<h2 class=\"wp-block-heading\">Brute force<\/h2>\n<p>def brute(prices):<br \/>\n    return max([0] + [prices[j]-prices[i]<br \/>\n        for i in range(len(prices))<br \/>\n        for j in range(i+1,len(prices))])<\/p>\n<h2 class=\"wp-block-heading\">Optimized or iterative approach<\/h2>\n<p class=\"wp-block-paragraph\">Track the cheapest price seen so far, rather than comparing every pair.<\/p>\n<p>def max_profit(prices):<br \/>\n    low = float(&#8220;inf&#8221;)<br \/>\n    best = 0<br \/>\n    for price in prices:<br \/>\n        low = min(low, price)<br \/>\n        best = max(best, price &#8211; low)<br \/>\n    return best<\/p>\n<h2 class=\"wp-block-heading\">Step-by-step walkthrough<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<p>DayPriceMinimumBest profit177021103514431456156415<\/p>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Correctness argument<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Complexity analysis<\/h2>\n<p class=\"wp-block-paragraph\">Brute force O(n\u00b2) time and O(n\u00b2) space for the list shown; optimized O(n) time and O(1) space.<\/p>\n<h2 class=\"wp-block-heading\">Edge cases<\/h2>\n<p class=\"wp-block-paragraph\">Descending prices, one price, equal prices, and a late minimum.<\/p>\n<h2 class=\"wp-block-heading\">Interview follow-ups<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Practice and revision<\/h2>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/leetcode.com\/problems\/best-time-to-buy-and-sell-stock\/\" target=\"_blank\" rel=\"noopener\">Original problem<\/a> \u00b7 <a href=\"https:\/\/programesecure.com\/dsa-roadmap\/\">DSA Roadmap<\/a><\/p>\n<h2 class=\"wp-block-heading\">Common mistakes and interview questions<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Practice variations and quick revision<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>","protected":false},"excerpt":{"rendered":"<p>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 \u2212 1 = 5. Difficulty: Easy \u00b7 Pattern: Greedy \/ prefix minimum \u00b7 Prerequisites: arrays and loops. Assume nonnegative integer prices; an empty input returns zero. Only one transaction [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":10595,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-10594","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10594"}],"collection":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10594"}],"version-history":[{"count":0,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10594\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/media\/10595"}],"wp:attachment":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10594"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10594"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10594"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}