【问题标题】:Find the max profit (max - min) in an array of values using c++使用c ++在值数组中查找最大利润(max - min)
【发布时间】:2015-02-18 15:50:21
【问题描述】:

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

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

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

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++ 中编码的最佳方法
谢谢。

【问题讨论】:

  • 不适用于2 100 1 2
  • 它们没有排序 - 它们需要保持原样,因为您只能在购买后出售。所以必须在最小值之后找到最大值。目标是找到最大的差异,因此最大值必须在最小值之后

标签: c++ arrays max min


【解决方案1】:
// 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;
  }
}

【讨论】:

    【解决方案2】:

    你可以试试:

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

    【讨论】:

    • 如果最小值不是 v[0] 或数组 [0] 而是一天中的最小值,这将如何变化。
    • @YelizavetaYR:它逐步找到最小值。它以v[0] 是最小值的假设开始,然后在找到“更好”(或更低)的最小值时更新最小值。如果v[0] 不是真正的最小值,它最终会找出并更新最小值为真正的最小值。
    • 在 for 循环中 - 什么是 e?
    • @Cornstalks 你需要一个在最大值之前发生的最小值。即2 100 1 98 的最大利润为 98。我认为您正确地找到了最大利润,但您会确定错误的购买时间。
    • 我用for range,你可以用for (std::size_t i = 0; i != v.size(); ++i) { const int e = v[i]; ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多