Optimal Stock Buying and Selling for Maximum Profit

🚀 𝗖𝗿𝗮𝗰𝗸𝗶𝗻𝗴 𝘁𝗵𝗲 “𝗕𝗲𝘀𝘁 𝗧𝗶𝗺𝗲 𝘁𝗼 𝗕𝘂𝘆 𝗮𝗻𝗱 𝗦𝗲𝗹𝗹 𝗦𝘁𝗼𝗰𝗸” 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 💡 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 You’re given stock prices where: prices[i] = price on day i 👉 Goal: Buy once and sell once (in the future) to get maximum profit 📌 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 Input: [4, 2, 3, 4, 5, 2] Output: 3 ✔ Buy at 2 → Sell at 5 🧠 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝟭: 𝗕𝗿𝘂𝘁𝗲 𝗙𝗼𝗿𝗰𝗲 (𝗢(n²)) Check every possible pair of buy & sell days ❌ Inefficient for large data ⚡ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝟮: 𝗧𝘄𝗼 𝗣𝗼𝗶𝗻𝘁𝗲𝗿 / 𝗦𝗹𝗶𝗱𝗶𝗻𝗴 𝗪𝗶𝗻𝗱𝗼𝘄 (𝗢(n)) Track buy and sell pointers Update buy when a smaller price appears ✔ Better performance with linear time 🔥 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝟯: 𝗢𝗽𝘁𝗶𝗺𝗮𝗹 (𝗚𝗿𝗲𝗲𝗱𝘆 - 𝗢(n)) Track minimum price so far Calculate profit at each step ✔ Most efficient and clean solution 💻 𝗢𝗽𝘁𝗶𝗺𝗮𝗹 𝗖𝗼𝗱𝗲 def optimal_stock(prices): min_price = float("inf") max_profit = 0 for price in prices: min_price = min(min_price, price) profit = price - min_price max_profit = max(max_profit, profit) return max_profit 🔗 𝗚𝗶𝘁𝗛𝘂𝗯 𝗖𝗼𝗱𝗲: https://lnkd.in/g-iaHxs5 🎯 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 Always track the minimum before maximum Greedy approach often gives optimal results in linear time 💬 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗶𝗽 Start with brute force → optimize step by step This shows strong problem-solving skills 💡 #DataStructures #Algorithms #CodingInterview #Python #LeetCode #SoftwareEngineering #ProblemSolving #GreedyAlgorithm

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories