class StockTrader {
prices: number[];
maxTransactions: number;
constructor(prices: number[], maxTransactions: number) {
this.prices = prices;
this.maxTransactions = maxTransactions;
}
maxProfit(): number {
const n = this.prices.length;
if (n === 0) return 0;
// dp[t][d] = max profit up to day d with at most t transactions
const dp: number[][] = Array.from({ length: this.maxTransactions + 1 }, () => Array(n).fill(0));
for (let t = 1; t <= this.maxTransactions; t++) {
let maxDiff = -this.prices[0];
for (let d = 1; d < n; d++) {
dp[t][d] = Math.max(dp[t][d - 1], this.prices[d] + maxDiff);
maxDiff = Math.max(maxDiff, dp[t - 1][d - 1] - this.prices[d]);
}
}
return dp[this.maxTransactions][n - 1];
}
}
// Driver code
const prices = [7, 1, 5, 3, 6, 4];
const maxTransactions = 2;
const trader = new StockTrader(prices, maxTransactions);
console.log(trader.maxProfit());const dp: number[][] = Array.from({ length: this.maxTransactions + 1 }, () => Array(n).fill(0));
Create a table to store max profit for each transaction count and day
for (let t = 1; t <= this.maxTransactions; t++) {
Iterate over number of transactions allowed
let maxDiff = -this.prices[0];
Track max difference between previous profits and price to optimize buying
dp[t][d] = Math.max(dp[t][d - 1], this.prices[d] + maxDiff);
Decide to sell today or skip selling
maxDiff = Math.max(maxDiff, dp[t - 1][d - 1] - this.prices[d]);
Update maxDiff to consider buying at current day