#121
Best Time to Buy and Sell Stock
EasyArrayDynamic ProgrammingArrayDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution tracks the minimum price seen so far while iterating through the prices. This allows us to calculate the potential profit in constant time, leading to a much more efficient solution.
⚙️
Algorithm
5 steps- 1Step 1: Initialize min_price to infinity and max_profit to 0.
- 2Step 2: Loop through each price in the prices array.
- 3Step 3: For each price, update min_price if the current price is lower than min_price.
- 4Step 4: Calculate the profit as current price - min_price. If this profit is greater than max_profit, update max_profit.
- 5Step 5: After the loop, return max_profit.
solution.py13 lines
1# Full working Python code
2prices = [7,1,5,3,6,4]
3def maxProfit(prices):
4 min_price = float('inf')
5 max_profit = 0
6 for price in prices:
7 if price < min_price:
8 min_price = price
9 profit = price - min_price
10 if profit > max_profit:
11 max_profit = profit
12 return max_profit
13print(maxProfit(prices))ℹ
Complexity note: This complexity is achieved because we only make a single pass through the prices array, updating our min_price and max_profit in constant time.
- 1The key to maximizing profit is to always buy at the lowest price before selling.
- 2You only need to keep track of the minimum price seen so far to calculate potential profits efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.