Best Time to Buy And Sell Stock
Detailed guide and Python implementation for the 'Best Time to Buy And Sell Stock' problem.
1. Concept Overview
The 'Best Time to Buy And Sell Stock' problem is a key challenge in the Sliding Window section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Best Time to Buy And Sell Stock.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Best Time to Buy And Sell Stock carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Problem Statement
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Write a function maxProfit(prices: List[int]) -> int.
- •1 <= len(prices) <= 10^5
- •0 <= prices[i] <= 10^4
Examples
prices = [7, 1, 5, 3, 6, 4]
5
Buy on day 2 (price = 1) and sell on day 5 (price = 6). Profit = 6 - 1 = 5.
prices = [7, 6, 4, 3, 1]
0
No profitable transaction is possible since prices only decrease.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
def max_profit_opt(prices):
l, r = 0, 1 # l:buy, r:sell
maxP = 0
while r < len(prices):
if prices[l] < prices[r]:
profit = prices[r] - prices[l]
maxP = max(maxP, profit)
else:
l = r
r += 1
return maxPBrute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
def max_profit_brute(prices):
res = 0
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
profit = prices[j] - prices[i]
res = max(res, profit)
return resAlgorithm Pattern Checklist
When dealing with Sliding Window data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Try/Except & Error Handling
Prevent your Python scripts from crashing. Learn try, except, finally blocks and how to raise custom exceptions properly.
How to Convert String to Int in Python
Learn how to convert a string to an integer in Python using the int() function. Handle errors safely and convert numbers from binary, octal, or hex.
Python DateTime Formatting
Learn how to parse and format dates and times in Python using datetime, strftime, and strptime.
Python Decorators vs Decorator Design Pattern: The Key Differences
Compare Python decorators and the classic decorator design pattern. Understand the differences between definition-time function wrapping and runtime dynamic object composition with runnable code.