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 and a single day to sell. Return the maximum profit you can achieve. Test.
Intuition
As we scan left to right, we track the lowest price we've seen. At each position, the best profit we could get by selling today is prices[i] - minPrice. We keep a running maximum of this value.
Approach (Greedy)
- Initialize
minPriceto the first price andmaxProfitto 0. - For each subsequent price, update
minPriceif the current price is lower. - Otherwise, compute profit and update
maxProfitif it's higher. - Return
maxProfit.
Solution
TypeScript
function maxProfit(prices: number[]): number {
let minPrice = prices[0];
let maxProfit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else {
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
}
}
return maxProfit;
}
Complexity Analysis
| Metric | Value | Explanation |
|---|---|---|
| Time | Single pass through the array | |
| Space | Only two variables tracked |