LeetCode 121 Best Time to Buy and Sell Stock (Python) | One Pass 📈 | #programming
LeetCode 121 Best Time to Buy and Sell Stock, explained in one pass with Python 🐍 Remember the cheapest price so far and ask every day: "what if I sold today?" O(n) time, O(1) space. 📌 Example: prices = [7, 1, 5, 3, 6, 4] → buy at 1, sell at 6, profit 5. ❌ The trap: "buy at the lowest, sell at the highest" fails. Here the highest price (7) comes BEFORE the lowest (1). You can't sell before you buy. 🐌 Two loops (every buy day × every sell day) works, but 100,000 days = about five billion pairs: Time Limit Exceeded. ✅ The trick: walk the days once. Keep the cheapest price so far, and the best profit if you sold today. 💡 3 tips: 1. Start best at 0. If prices only fall ([7, 6, 4, 3, 1]), you never trade and 0 is the right answer. 2. Pattern: when today's answer needs the best of the past, carry a running minimum. 3. Interview flex: it's Kadane's algorithm on the daily price changes (-6, +4, -2, +3, -2 → best run = 5). 🎯 Play along: [3, 8, 1, 5], one trade. The cheapest day (1) is NOT the buy day. Answer: 5 (buy 3, sell 8). 💻 Code (Python): def maxProfit(prices): cheapest = prices[0] best = 0 for p in prices: cheapest = min(cheapest, p) best = max(best, p - cheapest) return best 📚 Problem 7 of LeetCode's Top Interview 150, in order. Next: Best Time to Buy and Sell Stock II (unlimited trades). Logos: Simple Icons (CC0); trademarks belong to their owners. Animated emoji: Noto Emoji Animation by Google, CC BY 4.0. #leetcode #python #shorts #besttimetobuy #buyandsell #codinginterview #LeetCode121 #TopInterview150 #dsa #algorithms #learntocode #interviewpreparation #programming
Know someone who'd love this clip?
Share it with friends and fellow fans.



