function maxProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (const price of prices) {
if (price < minPrice) minPrice = price;
else if (price - minPrice > maxProfit) maxProfit = price - minPrice;
}
return maxProfit;
}
console.log(maxProfit([7,1,5,3,6,4]));The code finds the lowest price first and then calculates the maximum difference (profit) by subtracting the lowest price from the current price. The maximum profit is 5 (buy at 1, sell at 6).
function maxProfit(prices) {
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
console.log(maxProfit([7,1,5,3,6,4]));The code sums all increases between consecutive days: (5-1)+(6-3) = 4 + 3 = 7.
function maxProfit(prices) {
if (prices.length === 0) return 0;
let sell = 0, prev_sell = 0, buy = -Infinity;
for (const price of prices) {
let prev_buy = buy;
buy = Math.max(prev_sell - price, buy);
prev_sell = sell;
sell = Math.max(prev_buy + price, sell);
}
return sell;
}
console.log(maxProfit([1,2,3,0,2]));The code uses dynamic programming to track buy and sell states with cooldown. The maximum profit is 3.
function maxProfit(prices, fee) {
let cash = 0, hold = -prices[0];
for (let i = 1; i < prices.length; i++) {
cash = Math.max(cash, hold + prices[i] - fee);
hold = Math.max(hold, cash - prices[i]);
}
return cash;
}
console.log(maxProfit([1,3,2,8,4,9], 2));The code tracks cash (profit without stock) and hold (profit with stock). The maximum profit after fees is 8.
In DP solutions, buy state updates from previous sell minus price, sell state updates from previous buy plus price minus fee, and cooldown is handled by not allowing immediate buy after sell.
