1. function maxProfit(k: number, prices: number[]): number {
    2. const cache: number[][][] = new Array(prices.length)
    3. .fill(0)
    4. .map(() => [Array(k).fill(-1), Array(k).fill(-1)]);
    5. function backtrack(day: number, status: number, times: number): number {
    6. // base case
    7. if (day >= prices.length || times >= k) {
    8. return 0;
    9. }
    10. if (cache[day][status][times] !== -1) {
    11. return cache[day][status][times];
    12. }
    13. if (status === 0) {
    14. // make progress 到哪里去, 去哪儿
    15. // status 未持有
    16. cache[day][status][times] = Math.max(
    17. -prices[day] + backtrack(day + 1, (status + 1) % 2, times),
    18. backtrack(day + 1, status, times)
    19. );
    20. } else {
    21. // 持有
    22. cache[day][status][times] = Math.max(
    23. prices[day] + backtrack(day + 1, (status + 1) % 2, times + 1),
    24. backtrack(day + 1, status, times)
    25. );
    26. }
    27. return cache[day][status][times];
    28. }
    29. return backtrack(0, 0, 0);
    30. }