From b6e458bcfa3be2f8b7f282f5918f9bc26512e9fd Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Sun, 10 Mar 2024 21:47:48 +0800 Subject: [PATCH] =?UTF-8?q?Update=200121.=E4=B9=B0=E5=8D=96=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0121.买卖股票的最佳时机新增C语言实现 --- problems/0121.买卖股票的最佳时机.md | 47 +++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index cbdf40e8..fb548cbc 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -531,6 +531,52 @@ public class Solution } ``` +### C: + +> 贪心 + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min(a, b) ((a) > (b) ? (b) : (a)) + +int maxProfit(int* prices, int pricesSize) { + int low = INT_MIN; + int result = 0; + for(int i = 0; i < pricesSize; i++){ + low = min(low, prices[i]); + result = max(result, prices[i] - low); + } + return result; +} +``` + +> 动态规划 + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int maxProfit(int* prices, int pricesSize){ + if(pricesSize == 0){ + return 0; + } + // dp初始化 + int ** dp = malloc(sizeof (int *) * pricesSize); + for(int i = 0; i < pricesSize; i++){ + dp[i] = malloc(sizeof (int ) * 2); + } + // 下标0表示持有股票的情况下的最大现金,下标1表示不持有股票的情况下获得的最大现金 + dp[0][0] = -prices[0]; + dp[0][1] = 0; + for(int i = 1; i < pricesSize; i++){ + dp[i][0] = max(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]; +} +``` + + + ### Rust: > 贪心 @@ -568,4 +614,3 @@ impl Solution { -