Overview
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 different day in the future to sell. Return the maximum profit you can achieve. If no profit is possible, return 0.
Implement maxProfit(prices).
Constraints
1 ≤ prices.length ≤ 1000000 ≤ prices[i] ≤ 10000- You must buy before you sell (buy day < sell day).
- Only one transaction allowed.
- Aim for $O(n)$ time, $O(1)$ space.
Examples
maxProfit([7, 1, 5, 3, 6, 4]); // → 5 — buy on day 1 (price 1), sell on day 4 (price 6) → 6 - 1 = 5 maxProfit([7, 6, 4, 3, 1]); // → 0 — prices only decrease, no profitable transaction maxProfit([2, 4, 1]); // → 2 — buy day 0, sell day 1
Notes
- Track the minimum price seen so far. At each day, compute the profit if you sold today (
price - minSoFar) and track the global max. - Single pass, constant space.
Solution
Reveal solution
function maxProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (const price of prices) {
if (price < minPrice) {
minPrice = price;
} else {
maxProfit = Math.max(maxProfit, price - minPrice);
}
}
return maxProfit;
}Resources
optimal-stock-trading.js
Optimal Stock Trading
easycodingAlgorithmsDynamic Programming
Overview
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 different day in the future to sell. Return the maximum profit you can achieve. If no profit is possible, return 0.
Implement maxProfit(prices).
Constraints
1 ≤ prices.length ≤ 1000000 ≤ prices[i] ≤ 10000- You must buy before you sell (buy day < sell day).
- Only one transaction allowed.
- Aim for $O(n)$ time, $O(1)$ space.
Examples
maxProfit([7, 1, 5, 3, 6, 4]); // → 5 — buy on day 1 (price 1), sell on day 4 (price 6) → 6 - 1 = 5 maxProfit([7, 6, 4, 3, 1]); // → 0 — prices only decrease, no profitable transaction maxProfit([2, 4, 1]); // → 2 — buy day 0, sell day 1
Notes
- Track the minimum price seen so far. At each day, compute the profit if you sold today (
price - minSoFar) and track the global max. - Single pass, constant space.
Solution
Reveal solution
function maxProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (const price of prices) {
if (price < minPrice) {
minPrice = price;
} else {
maxProfit = Math.max(maxProfit, price - minPrice);
}
}
return maxProfit;
}Resources
NameTopicDifficulty
103 of 103 problems