1. function maxProfit(prices: number[]): number {
    2. const cache: number[][][] = Array(prices.length)
    3. .fill(0)
    4. .map(() => [
    5. [NaN, NaN],
    6. [NaN, NaN],
    7. ]);
    8. function backtrack(day: number, status: number, freeze: boolean): number {
    9. // base case
    10. if (day >= prices.length) {
    11. return 0;
    12. }
    13. // 是否是冷冻期
    14. if (freeze) {
    15. return backtrack(day + 1, status, !freeze);
    16. }
    17. // 命中缓存
    18. if (!Number.isNaN(cache[day][status][0])) {
    19. return cache[day][status][0];
    20. }
    21. if (status === 0) {
    22. // 非持有状态
    23. cache[day][status][0] = Math.max(
    24. -prices[day] + backtrack(day + 1, (status + 1) % 2, false),
    25. backtrack(day + 1, status, false)
    26. );
    27. } else {
    28. // 持有状态
    29. cache[day][status][0] = Math.max(
    30. prices[day] + backtrack(day + 1, (status + 1) % 2, true),
    31. backtrack(day + 1, status, false)
    32. );
    33. }
    34. return cache[day][status][0];
    35. // make progress
    36. }
    37. return backtrack(0, 0, false);
    38. }