121. Best Time to Buy and Sell Stock
You are given an array prices
where prices[i]
represents the price of a stock on the i
-th day.
Your goal is to maximize profit by choosing exactly one day to buy and a different later day to sell the stock.
Return the maximum profit you can achieve from the transaction.
If no profit is possible, 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: You cannot buy on day 2 and sell on day 1 because the selling day must come after the buying day.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: The price always drops, so no transaction yields a profit.
Constraints:
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^4
Instead of checking every possible buy-sell pair, which would be O(n^2)
, we track two things in one pass:
- The lowest price seen so far (
minPrice
) - The maximum profit we can make so far (
maxProfit
)
On each day:
- If the current price is lower than
minPrice
, updateminPrice
(this could be a better buy day). - Otherwise, calculate
price - minPrice
(profit if sold today), and if it's larger thanmaxProfit
, updatemaxProfit
.
JavaScript Solution:
var maxProfit = function(prices) {
let minPrice = Number.MAX_SAFE_INTEGER;
let maxProfit = 0;
for (let price of prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
};
TypeScript Solution:
function maxProfit(prices: number[]): number {
let minPrice = Number.MAX_SAFE_INTEGER;
let maxProfit = 0;
for (let price of prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
}