ArrayProblem 17 of 36
Best time to buy and Sell stock
Problem Statement
Given an array of stock prices where prices[i] is the price on day i, find the maximum profit you can achieve from one transaction (buy one and sell one share). You must buy before you sell.
Example:
- Input:
[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
Approach 1: Brute Force
Intuition
For each day, consider buying on that day and selling on every future day. Track the maximum profit.
Algorithm
- For each day
i(buying day) - For each day
j > i(selling day) - Calculate profit =
prices[j] - prices[i] - Track maximum profit
java
public class Solution {
public int maxProfitBruteForce(int[] prices) {
int n = prices.length;
int maxProfit = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int profit = prices[j] - prices[i];
maxProfit = Math.max(maxProfit, profit);
}
}
return maxProfit;
}
}Complexity Analysis
- Time Complexity: O(n²) - Checking all pairs of days
- Space Complexity: O(1) - No extra space used
Approach 2: Single Pass (Optimal)
Intuition
To maximize profit, we want to buy at the lowest price and sell at the highest price after that. As we traverse, we track the minimum price seen so far and calculate the potential profit at each step.
Algorithm
- Initialize
minPriceto infinity andmaxProfitto 0 - For each price:
- Update
minPriceif current price is lower - Calculate profit if we sell today:
price - minPrice - Update
maxProfitif this profit is higher
- Update
- Return
maxProfit
java
public class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
// Update minimum price seen so far
minPrice = Math.min(minPrice, price);
// Calculate profit if we sell today
int profit = price - minPrice;
// Update maximum profit
maxProfit = Math.max(maxProfit, profit);
}
return maxProfit;
}
}Complexity Analysis
- Time Complexity: O(n) - Single pass through the array
- Space Complexity: O(1) - Only two variables used
Visual Example
For array [7, 1, 5, 3, 6, 4]:
Day 1: price = 7
minPrice = 7, profit = 0, maxProfit = 0
Day 2: price = 1
minPrice = 1, profit = 0, maxProfit = 0
Day 3: price = 5
minPrice = 1, profit = 5-1 = 4, maxProfit = 4
Day 4: price = 3
minPrice = 1, profit = 3-1 = 2, maxProfit = 4
Day 5: price = 6
minPrice = 1, profit = 6-1 = 5, maxProfit = 5
Day 6: price = 4
minPrice = 1, profit = 4-1 = 3, maxProfit = 5
Final: maxProfit = 5 (Buy at 1, Sell at 6)
Alternative: Kadane's Algorithm Perspective
This problem can be transformed into finding maximum subarray sum of daily differences.
Key Takeaways
- Track the minimum while iterating - Classic single-pass optimization pattern
- The problem is essentially: find
max(prices[j] - prices[i])wherej > i - Greedy approach works because we always want to buy at the lowest point before selling
- If no profit is possible (prices only decrease), return 0
- This is a foundation for more complex stock problems (multiple transactions, cooldown, etc.)
- Connection to Kadane's: Sum of daily differences equals total price change