如何获得数值数组中从低值减去高值的最高范围? [英] How to get the highest range from low value minus high value within an array of numbers?

查看:280
本文介绍了如何获得数值数组中从低值减去高值的最高范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我们有一个销售人员来到一个商店,该商店有一系列不同价格的产品数量。

So we have a sales person who comes to a shop that has an array of numbers of products with different prices.

vector<int> prices{28, 18, 20, 26, 24, 12};



问题



选择具有最低值的产品和具有最低值的索引之后的最高值,但也要记住最低值不是数组中的最后一个元素(但最高值可以在最后一个元素中) 。所以我们的最低值将是18,并以最高的价值卖出,这将是26。

Problem

We need this sales person to select the product with the lowest value first and the highest value after the index with the lowest value, but also putting in mind that the lowest value is not the last element in the array (however the highest value can be in the last element). So our lowest value will be 18 and sell it with the highest value, which will be 26.

但这里棘手的部分是它需要有最大的利润。
例如,26是最高值,26 - 18 = 8。

But the tricky part here is that it needs to have the maximum profit. So for example 26 is the highest value, and 26 - 18 = 8.

但是会有最高 - 。

我们如何确保最大利润从上面的数组中取出? / p>

How can we make sure that the maximum profit is taken out of the array above?

  for (int i = 0; i < vec.size(); i++) {
    if ((vec[i] <= _minVal)) {
      _newMinIndex = i;
      if (_newMinIndex == vec.size() - 1) {
        _minVal = 0;
        _newMinIndex = 0;
      } else {
        _minVal = vec[i];
      }
    }
  }

  for (int i = 0; i < vec.size(); i++) {
    max = vec[_newMinIndex];
    min = vec[_newMinIndex];
    increment = _newMinIndex;
    while (increment < vec.size()) {
      if (vec[increment] > max) {
        max = vec[increment];
        maxIndex = increment;
      }
      increment++;
    }
  }



我有两个for循环,第一个循环最小值第一,第二个for循环从minium加索引到数组结尾有最高值。

I have two for loops, the first loop gets the minimum value first, and the second for loop gets the highest value from the index of minium plus till the end of the array.

这将工作,但它不会

推荐答案

p>因为你的代码使我困惑,这里是我的,你做的每个规则:

Since your code confuses me, here is mine, with every rules you made:

    std::vector<int> prices = { 28, 18, 20, 26, 24, 12 };

int min = 0, min_index = -1;
for (int i = 0; i < prices.size(); i++)
    if (i != prices.size() - 1)
        if (!min || prices[i] < min) {
            min = prices[i];
            min_index = i;
        }

if (min != -1) {
    int max = min;
    for (int i = min_index + 1; i < prices.size(); i++)
        if (prices[i] > max)
            max = prices[i];

    if (max != min) //Remove this to also print null profits
        std::cout << "profit :" << max-min << std::endl;
}

这篇关于如何获得数值数组中从低值减去高值的最高范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆