function maxProfit(k: number, prices: number[]): number { const cache: number[][][] = new Array(prices.length) .fill(0) .map(() => [Array(k).fill(-1), Array(k).fill(-1)]); function backtrack(day: number, status: number, times: number): number { // base case if (day >= prices.length || times >= k) { return 0; } if (cache[day][status][times] !== -1) { return cache[day][status][times]; } if (status === 0) { // make progress 到哪里去, 去哪儿 // status 未持有 cache[day][status][times] = Math.max( -prices[day] + backtrack(day + 1, (status + 1) % 2, times), backtrack(day + 1, status, times) ); } else { // 持有 cache[day][status][times] = Math.max( prices[day] + backtrack(day + 1, (status + 1) % 2, times + 1), backtrack(day + 1, status, times) ); } return cache[day][status][times]; } return backtrack(0, 0, 0);}