Complete the code to find the maximum profit from a single buy-sell transaction.
function maxProfit(prices: number[]): number {
let minPrice = Infinity;
let maxProfit = 0;
for (let i = 0; i < prices.length; i++) {
if (prices[i] < [1]) {
minPrice = prices[i];
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}We update minPrice when we find a price lower than the current minimum. So the condition checks if prices[i] is less than minPrice.
Complete the code to calculate maximum profit with unlimited transactions (buy and sell multiple times).
function maxProfit(prices: number[]): number {
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > [1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}We buy at prices[i - 1] and sell at prices[i] if the price increased, so we check if prices[i] is greater than prices[i - 1].
Fix the error in the code to find max profit with at most two transactions.
function maxProfit(prices: number[]): number {
let firstBuy = Infinity, firstProfit = 0;
let secondBuy = Infinity, secondProfit = 0;
for (const price of prices) {
firstBuy = Math.min(firstBuy, price);
firstProfit = Math.max(firstProfit, price - firstBuy);
secondBuy = Math.min(secondBuy, price - [1]);
secondProfit = Math.max(secondProfit, price - secondBuy);
}
return secondProfit;
}When calculating secondBuy, we subtract the profit from the first transaction (firstProfit) to simulate reinvesting that profit.
Fill both blanks to implement max profit with cooldown (cannot buy immediately after selling).
function maxProfit(prices: number[]): number {
let sell = 0, prevSell = 0, buy = -Infinity, prevBuy;
for (const price of prices) {
prevBuy = buy;
buy = Math.max(prevBuy, [1] - price);
prevSell = sell;
sell = Math.max(prevSell, [2] + price);
}
return sell;
}For buying, we compare previous buy and previous sell minus current price (prevSell - price), so buy = Math.max(prevBuy, prevSell - price).
For selling, we compare previous sell and previous buy plus current price (prevBuy + price), so sell = Math.max(prevSell, prevBuy + price).
Fill both blanks to implement max profit with transaction fee.
function maxProfit(prices: number[], fee: number): number {
let cash = 0, hold = -prices[0];
for (let i = 1; i < prices.length; i++) {
cash = Math.max(cash, hold + prices[i] - [1]);
hold = Math.max(hold, cash - [2]);
}
return cash;
}When selling, we pay the transaction fee, so subtract fee from the price.
When buying, we subtract the current price from cash.