• 和买卖股票2高度类似

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