Leetcode 714 买卖股票的最佳时机含手续费 dp

C:
#include <stdio.h> #include <stdlib.h> int dp(int *prices, int fee, int point, int hasShared, int *cache) { if (point == 0) { if (hasShared == 0) return 0; else return -prices[0]; } int key = point * 2 + hasShared; if (cache[key] != 0) return cache[key]; int re = 0; if (hasShared == 0) { int seal = dp(prices, fee, point - 1, 1, cache) + prices[point] - fee; int keep = dp(prices, fee, point - 1, 0, cache); re = seal > keep ? seal : keep; } else { int add = dp(prices, fee, point - 1, 0, cache) - prices[point]; int keep = dp(prices, fee, point - 1, 1, cache); re = add > keep ? add : keep; } cache[key] = re; return re; } int maxProfit(int *prices, int pricesSize, int fee) { int len = pricesSize * 2; int *cache = (int *)malloc(sizeof(int) * len); for (int i = 0; i < len; i++) cache[i] = 0; int re = dp(prices, fee, pricesSize - 1, 0, cache); free(cache); return re; }
JAVA:
public final int maxProfit(int[] prices, int fee) { int len = prices.length; int[][] cache = new int[len][2]; return max(prices, fee, len - 1, 0, cache); } private final int max(int[] prices, int fee, int point, int hasShares, int[][] cache) { if (point == 0 && hasShares == 0) return 0; if (point == 0 && hasShares == 1) return -prices[0]; if (cache[point][hasShares] != 0) return cache[point][hasShares]; int re; if (hasShares == 0) { re = Math.max(max(prices, fee, point - 1, 0, cache), max(prices, fee, point - 1, 1, cache) + prices[point] - fee); } else { re = Math.max(max(prices, fee, point - 1, 1, cache), max(prices, fee, point - 1, 0, cache) - prices[point]); } cache[point][hasShares] = re; return re; }
JS:
/** * @param {number[]} prices * @param {number} fee * @return {number} */ var maxProfit = function (prices, fee) { let cache = new Array(prices.length); for (let i = 0; i < prices.length; i++) cache[i] = new Array(2).fill(0); return dp(prices, fee, prices.length - 1, 0, cache); }; var dp = function (prices, fee, point, hasShared, cache) { if (point == 0) { if (hasShared == 0) return 0; else return -prices[0]; } if (cache[point][hasShared]) return cache[point][hasShared]; let re = 0; if (hasShared) { let get = dp(prices, fee, point - 1, 0, cache) - prices[point]; let keep = dp(prices, fee, point - 1, 1, cache); re = get > keep ? get : keep; } else { let seal = dp(prices, fee, point - 1, 1, cache) + prices[point] - fee; let keep = dp(prices, fee, point - 1, 0, cache); re = seal > keep ? seal : keep; } cache[point][hasShared] = re; return re; }
当你看清人们的真相,于是你知道了,你可以忍受孤独
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构