Back to Browse

LeetCode 121 | Best Time to Buy & Sell Stock | Java One-Pass Solution Explained

58 views
Nov 20, 2025
8:45

In this video, we solve LeetCode 121 – Best Time to Buy and Sell Stock using Java with a simple and optimal one-pass approach. We track the minimum price so far and calculate profit at each step, updating the maximum profit dynamically. This matches real interview expectations and avoids brute-force methods. πŸ’» Code Used in Video (Exact) int buyPrice = Integer.MAX_VALUE; int maxProfit = 0; int profit = 0; for (int val : prices) { buyPrice = Math.min(buyPrice, val); profit = val - buyPrice; maxProfit = Math.max(maxProfit, profit); } return maxProfit; 🧠 Key Concepts Track lowest stock price while iterating Compute profit on each day using (price - buyPrice) Update maxProfit when a higher value is found Time Complexity: O(n) Space Complexity: O(1) πŸ“ˆ Example Used Input: [7, 1, 5, 3, 6, 4] Output: 5 (Buy at 1, Sell at 6) 🎯 Who Should Watch Java learners preparing for coding interviews LeetCode problem solvers Students learning stock profit logic in DSA Anyone preparing for interviews or learning and practicing coding

Download

0 formats

No download links available.

LeetCode 121 | Best Time to Buy & Sell Stock | Java One-Pass Solution Explained | NatokHD