gpt4 book ai didi

c++ - 使用 C++ 在值数组中查找最大利润 (max - min)

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:04 25 4
gpt4 key购买 nike

我有一个项目,内容如下:

给定一天内按时间顺序排列的一系列股票价格。找出先买入再卖出股票可能获得的最大利润。该函数接收指向数组的指针和相应的数组大小。

基本上我必须找到一个最小值,然后找到一个最大值(具有更高的索引)以产生最大可能的利润。最大 - 最小。

Sample data:
price[0]=100;
price[1]=5;
price[2]=7;
price[3]=34;
price[4]=100;
price[5]=2;

Output Based on Sample Data:
The best possible profit would be if one bought at point 1 and sold at point 4 for 100-5 = 95 a share.

我在想 - 我有两个小的 min 和 max 函数。
Min 函数查找返回最小位置索引的最小值。
然后我们将指针移动到 min_index +1 并将其传递给函数以找到最大值。然后max函数返回max_index;然后我们将取 max_index 值并减去 min_index 值。我不知道这是不是最好的方法,甚至是好的方法。我也不完全确定用 C++ 编写代码的最佳方法
谢谢。

最佳答案

你可以试试:

int bestProfit(const std::vector<int>& v)
{
if (v.empty()) {
return 0;
}
int min = v[0];
int profit = 0;
for (auto e : v) {
profit = std::max(profit, e - min);
min = std::min(min, e);
}
return profit;
}

关于c++ - 使用 C++ 在值数组中查找最大利润 (max - min),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27570630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com