已知n天后的股票行情,现在已有的本金是m, 规定只能入手一次股票和抛售一次股票。 最大收益是?C++完整
时间: 2024-04-17 14:25:22 浏览: 10
以下是一个用C++实现的完整示例:
```cpp
#include <iostream>
#include <vector>
int maxProfit(std::vector<int>& prices, int m) {
int n = prices.size();
int maxProfit = 0;
int buyPrice = prices[0];
for (int i = 1; i < n; i++) {
if (prices[i] < buyPrice) {
buyPrice = prices[i];
} else {
int profit = prices[i] - buyPrice;
if (profit > maxProfit) {
maxProfit = profit;
}
}
}
return maxProfit * m;
}
int main() {
std::vector<int> prices = {10, 7, 5, 8, 11, 9};
int m = 100;
int result = maxProfit(prices, m);
std::cout << result << std::endl;
return 0;
}
```
在上面的示例中,我们定义了一个名为`maxProfit`的函数,该函数接受股票价格的向量和本金作为参数,并返回最大收益。程序使用一个循环遍历股票价格列表,找到最低的买入价格,并计算与之后的每个价格相比的收益。如果收益大于当前最大收益,则更新最大收益。最后,将最大收益乘以本金返回。
在`main`函数中,我们定义了一个示例股票价格列表和本金,并调用`maxProfit`函数计算最大收益。结果将被打印到标准输出。
请根据实际情况修改股票价格列表和本金。