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