Best time to buy & sell stocks
Watch the walkthrough
Open on InstagramProblem
Choose at most one buy day and a later sell day to maximize profit. Return 0 if no profitable transaction exists.
Approach and revision checks
The first version checks all valid day pairs in O(n²) time. The second retains the minimum price seen so far and the best later profit in O(n) time, O(1) space. Running the complete file keeps the second definition. Example: [7, 1, 5, 3, 6, 4] -> 5. Test falling prices and a single price.
Original repository source
Copied from the supplied local DSA-Series checkout; code and comments are preserved. Run alternative definitions separately when comparing approaches.
5-best-time-to-buy-sell-stocks.js
var maxProfit = function (prices) {
let profit = 0;
let n = prices.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let diff = prices[j] - prices[i];
profit = Math.max(profit, diff);
}
}
return profit;
};
var maxProfit = function (prices) {
let min = prices[0];
let maxProfit = 0;
for (let i = 0; i < prices.length; i++) {
if (prices[i] < min) {
min = prices[i];
} else {
let profit = prices[i] - min;
maxProfit = Math.max(profit, maxProfit);
}
}
return maxProfit;
};