From 1b9ae455df706c170e6af3c73543a15f8fdbef79 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Tue, 12 Mar 2024 21:43:13 +0800 Subject: [PATCH] =?UTF-8?q?Update=200122.=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=BAII?= =?UTF-8?q?=EF=BC=88=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=EF=BC=89.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0122.买卖股票的最佳时机II新增C语言实现 --- ...票的最佳时机II(动态规划).md | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 6e08b57c..24c7f168 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -365,6 +365,49 @@ public class Solution } ``` +### C: + +> 动态规划 + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int maxProfit(int* prices, int pricesSize){ + 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], dp[i - 1][1] - prices[i]); + dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]); + } + return dp[pricesSize - 1][1]; +} +``` + +> 贪心 + +```c +int maxProfit(int* prices, int pricesSize) { + if(pricesSize == 0){ + return 0; + } + int result = 0; + for(int i = 1; i < pricesSize; i++){ + // 如果今天股票价格大于昨天,代表有利润 + if(prices[i] > prices[i - 1]){ + result += prices[i] - prices[i - 1]; + } + } + return result; +} +``` + + + ### Rust: > 贪心 @@ -416,3 +459,4 @@ impl Solution { +