Stock Buy and Sell
Problem Statement:β
You are given an array of prices where prices[i] is the price of a given stock on an 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.
Example 1:
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.
Note: That buying on day 2 and selling on day 1
is not allowed because you must buy before
you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are
done and the max profit = 0.
β Solution: Greedy / Single Pass (Best Time to Buy and Sell Stock)β
int maximumProfit(vector<int>& stockPrices) {
int lowestPriceSoFar = INT_MAX; // Track the minimum price (buying price)
int highestProfit = 0; // Track the max profit so far
for (int price : stockPrices) {
lowestPriceSoFar = min(lowestPriceSoFar, price); // Update min price
highestProfit = max(highestProfit, price - lowestPriceSoFar); // Update max profit
}
return highestProfit;
}
π How It Worksβ
- You're given a list of stock prices, and you must buy once and sell once to maximize profit.
- At each step:
- Update the lowest price seen so far (
lowestPriceSoFar). - Calculate profit:
current price - lowestPriceSoFar. - Update
highestProfitif the profit is better than before.
- Update the lowest price seen so far (
- All in one pass, making it highly efficient.
π§© Key Formulaβ
maxProfit = max(maxProfit, price[i] - minPriceSoFar)
minPriceSoFar = min(minPriceSoFar, price[i])
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| β± Time | O(n) |
| π Space | O(1) |
β οΈ Edge Casesβ
- All decreasing prices β profit = 0
- All prices same β profit = 0
- Only one price β profit = 0 (can't sell without buying before)
- Empty array β return 0 or handle with a guard
π‘ Other Approachesβ
| Approach | Time | Space | Notes |
|---|---|---|---|
| Brute Force | O(nΒ²) | O(1) | Compare all pairs, too slow β |
| Greedy (this) | O(n) | O(1) | β Best and optimal |
π Related Problemsβ
π¬