LeetCode-714 Posted on 2020-12-17 Edited on 2025-02-13 In LeetCode 题目 结果 代码DP之二维数组123456789101112class Solution { public int maxProfit(int[] prices, int fee) { int[][] dp = new int[prices.length][2]; dp[0][0] = 0; dp[0][1] = -prices[0]; for (int i = 1; i < dp.length; i++) { dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee); dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]); } return dp[dp.length - 1][0]; }} DP之一位数组×2123456789101112class Solution { public int maxProfit(int[] prices, int fee) { int[] dp1 = new int[prices.length]; int[] dp2 = new int[prices.length]; dp2[0] = -prices[0]; for (int i = 1; i < prices.length; i++) { dp1[i] = Math.max(dp1[i - 1], dp2[i - 1] + prices[i] - fee); dp2[i] = Math.max(dp2[i - 1], dp1[i - 1] - prices[i]); } return dp1[prices.length - 1]; }} DP之再优化1234567891011class Solution { public int maxProfit(int[] prices, int fee) { int a = 0; int b = -prices[0]; for (int i = 1; i < prices.length; i++) { a = Math.max(a, b + prices[i] - fee); b = Math.max(b, a - prices[i]); } return a; }} 复杂度时间复杂度:O(n) 空间复杂度:O(1)