From 652fa2bbb0a43799365df33544bf13638a6b8d20 Mon Sep 17 00:00:00 2001 From: Terry Liu <102352821+Lozakaka@users.noreply.github.com> Date: Fri, 9 Jun 2023 18:11:29 -0400 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Ejava=202*2=20array=20solution?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...佳时机含手续费(动态规划).md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md index 12789934..1443f147 100644 --- a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md +++ b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md @@ -154,6 +154,25 @@ class Solution { return dp[1]; } } +```Java +//使用 2*2 array +class Solution { + public int maxProfit(int[] prices, int fee) { + int dp[][] = new int[2][2]; + int len = prices.length; + //[i][0] = holding the stock + //[i][1] = not holding the stock + dp[0][0] = -prices[0]; + + for(int i = 1; i < len; i++){ + dp[i % 2][0] = Math.max(dp[(i - 1) % 2][0], dp[(i - 1) % 2][1] - prices[i]); + dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i] - fee); + } + + return dp[(len - 1) % 2][1]; + } +} +``` ``` Python: