Best Time to Buy and Sell Stock
Difficulty: Easy
Problem
Given an array prices where prices[i] is the price of a given stock on the ith day, find the maximum profit. You must buy before you sell.
Example
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Brute-force approach
Try every pair of buy and sell days to find maximum profit.
Steps
- For each buy day i
- Try every sell day j > i
- Calculate profit = prices[j] - prices[i]
- Track maximum profit
Time complexity: O(n²) · Space complexity: O(1)
Trade-offs
- Checking all pairs is slow
- Many pairs are clearly suboptimal
- Don't need to check all
Optimal approach
Key insight: Best profit at any day = today's price - minimum price seen before today.
Track minimum price seen so far. At each price, check if selling now gives better profit.
Steps
- Track minimum price seen
- At each price, update min if smaller
- Calculate profit if selling today
- Track maximum profit
Time complexity: O(n) · Space complexity: O(1)