Best Time to Buy and Sell Stock in Python and Java
In this tutorial, we will learn LeetCode #121: Best Time to Buy and Sell Stock in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Best Time to Buy and Sell Stock Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use one pass tracking the cheapest price because it gives a clean and optimized solution.
Example input: prices = [8, 3, 6, 2, 9, 5] Expected result: Output: 7 Explanation: Buy at 2 and sell at 9.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: prices = [8, 3, 6, 2, 9, 5] Approach: one pass tracking the cheapest price We update variables step by step until we reach: Output: 7
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why one pass tracking the cheapest price is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Start with the first price. prices = [8, 3, 6, 2, 9, 5] cheapest_price = 8 best_profit = 0 Step 2 Next price is 3. It is cheaper than 8. cheapest_price = 3 best_profit = 0 Step 3 Next price is 6. If we buy at 3 and sell at 6, profit is 3. profit = 6 - 3 profit = 3 best_profit = 3 Step 4 Later price is 2. This is the new cheapest price. cheapest_price = 2 Step 5 Next price is 9. If we buy at 2 and sell at 9, profit is 7. profit = 9 - 2 profit = 7 best_profit = 7 Final answer = 7
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: 7
Example 1
Input: prices = [8, 3, 6, 2, 9, 5] Output: Output: 7 Explanation: Buy at 2 and sell at 9.
Example 2
Input: prices = [10, 7, 5, 8, 11, 6] Output: 6 Explanation: Buy at 5 and sell at 11, so profit is 6.
Python Code
Here is the complete Python solution for LeetCode #121.
class StockProfitFinder:
def max_profit(self, prices):
cheapest_price = prices[0]
best_profit = 0
for price in prices:
cheapest_price = min(cheapest_price, price)
best_profit = max(best_profit, price - cheapest_price)
return best_profit
finder = StockProfitFinder()
print(finder.max_profit([8, 3, 6, 2, 9, 5])) # Output: 7
print(finder.max_profit([7, 6, 4, 3, 1])) # Output: 0Java Code
Here is the complete Java solution for LeetCode #121.
class StockProfitFinder {
public int maxProfit(int[] prices) {
int cheapestPrice = prices[0];
int bestProfit = 0;
for (int price : prices) {
cheapestPrice = Math.min(cheapestPrice, price);
bestProfit = Math.max(bestProfit, price - cheapestPrice);
}
return bestProfit;
}
public static void main(String[] args) {
StockProfitFinder finder = new StockProfitFinder();
System.out.println(finder.maxProfit(new int[] {8, 3, 6, 2, 9, 5})); // Output: 7
System.out.println(finder.maxProfit(new int[] {7, 6, 4, 3, 1})); // Output: 0
}
}Time and Space Complexity
Time Complexity: O(n log k)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(1)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #121: Best Time to Buy and Sell Stock becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.