From 1b935259a6c83beab9f730059da4bec509bb1f61 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Tue, 12 Apr 2022 21:01:23 +0100 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200122.=E4=B9=B0=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BAII.md=20C?= =?UTF-8?q?=E8=AF=AD=E8=A8=80=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0122.买卖股票的最佳时机II.md | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index 83b852c6..1b84f728 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -269,7 +269,7 @@ const maxProfit = (prices) => { ``` C: - +贪心: ```c int maxProfit(int* prices, int pricesSize){ int result = 0; @@ -284,5 +284,27 @@ int maxProfit(int* prices, int pricesSize){ } ``` +动态规划: +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) + +int maxProfit(int* prices, int pricesSize){ + int dp[pricesSize][2]; + dp[0][0] = 0 - prices[0]; + dp[0][1] = 0; + + int i; + for(i = 1; i < pricesSize; ++i) { + // dp[i][0]为i-1天持股的钱数/在第i天用i-1天的钱买入的最大值。 + // 若i-1天持股,且第i天买入股票比i-1天持股时更亏,说明应在i-1天时持股 + dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i]); + //dp[i][1]为i-1天不持股钱数/在第i天卖出所持股票dp[i-1][0] + prices[i]的最大值 + dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i]); + } + // 返回在最后一天不持股时的钱数(将股票卖出后钱最大化) + return dp[pricesSize - 1][1]; +} +``` + -----------------------