mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Update 0122.买卖股票的最佳时机II(动态规划).md
0122.买卖股票的最佳时机II新增C语言实现
This commit is contained in:
@ -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 {
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
Reference in New Issue
Block a user