简体   繁体   English

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

[英]Find the max profit (max - min) in an array of values using c++

I have a project that reads as follows: 我有一个项目,内容如下:

Given an array of stock prices during the span of a single day in chronological order. 给定一天中时间范围内的一系列股票价格。 Find the biggest profit that could have been made by first buying and then selling the stock. 找到先买入然后卖出股票所能获得的最大利润。 The function receives a pointer to an array, and a corresponding array size. 该函数接收指向数组的指针以及相应的数组大小。

Basically I have to find a min value, and then find a max value (with a higher index) to yield the biggest possible profit. 基本上,我必须找到一个最小值,然后找到一个最大值(具有较高的索引),以产生最大的利润。 Max - Min. 最高-最低

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.

I was thinking - I have two small min and max functions. 我在想-我有两个小的最小和最大功能。
The Min function finds the min value returning the index of the min position. Min函数找到返回最小值位置索引的最小值。
Then we have the pointer move to the min_index +1 and pass that to the function to find the max value. 然后,我们将指针移至min_index +1并将其传递给函数以找到最大值。 Then the max function returns the max_index; 然后max函数返回max_index; Then we would take the max_index value and subtract the min_index value. 然后,我们将采用max_index值并减去min_index值。 I don't know if this is the best approach or even a good approach. 我不知道这是最好的方法,还是好的方法。 I'm also not entirely sure of the best way to code this in c++ 我也不完全知道用c ++编写代码的最佳方法
Thank you. 谢谢。

You may try: 您可以尝试:

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;
}
// Time zero: Buy and sell at the same time, no profit
int best_buy_index = 0;
int best_sell_index = 0;
int min_index = 0;
int best_profit = 0;

for (int i = 1; i < prices.size(); ++i) {
  // Profit we'd get if we had bought at the lowest price yet and sold now.
  int profit = (prices[i] - prices[min_index]);

  if (profit > best_profit) {
    // We found a better solution.
    best_buy_index = min_index;
    best_sell_index = i;
    best_profit = profit;
  } else if (prices[i] < prices[min_index]) {
    // Potentially better buy time.
    min_index = i;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM