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

时间:2014-12-19 17:02:28

标签: c++ arrays 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.

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

2 个答案:

答案 0 :(得分:3)

您可以尝试:

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;
}

答案 1 :(得分:2)

// 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;
  }
}