c语言动态规划股票问题
时间: 2023-12-27 07:25:46 浏览: 35
动态规划是解决股票问题的一种常用方法。下面是一个使用动态规划解决股票问题的C语言示例:
```c
#include <stdio.h>
int maxProfit(int* prices, int pricesSize) {
if (pricesSize <= 1) {
return 0;
}
int minPrice = prices[0]; // 记录最低价格
int maxProfit = 0; // 记录最大利润
for (int i = 1; i < pricesSize; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i]; // 更新最低价格
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice; // 更新最大利润
}
}
return maxProfit;
}
int main() {
int prices[] = {7, 1, 5, 3, 6, 4};
int pricesSize = sizeof(prices) / sizeof(prices[0]);
int profit = maxProfit(prices, pricesSize);
printf("Max profit: %d\n", profit); // 输出:5
return 0;
}
```