From ec61f2430d3ab09f8dc1c998514dfc1ca77ba0bb Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:30:14 +0800 Subject: [PATCH] =?UTF-8?q?0122=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8?= =?UTF-8?q?=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA2=E6=B7=BB=E5=8A=A0Java?= =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...票的最佳时机II(动态规划).md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 3444ca73..c85272bc 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -133,7 +133,34 @@ public: Java: +```java +// 动态规划 +class Solution + public int maxProfit(int[] prices) { + int n = prices.length; + int[][] dp = new int[n][2]; + dp[0][0] = 0; + dp[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]); + dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]); + } + return dp[n - 1][0]; + } + public int maxProfit(int[] prices) { + int n = prices.length; + int dp0 = 0, dp1 = -prices[0]; + for (int i = 1; i < n; ++i) { + int newDp0 = Math.max(dp0, dp1 + prices[i]); + int newDp1 = Math.max(dp1, dp0 - prices[i]); + dp0 = newDp0; + dp1 = newDp1; + } + return dp0; + } +} +``` Python: