OOP OOP - 1 month ago 7
C++ Question

How to get the highest range from low value minus high value within an array of numbers?

Idea



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


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.

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.

But there will be instances where the highest - lowest != to maximum profit.

Task



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


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.

This will work, but it doesnt take into account with the maximum profit.

How can we implement this.

Answer

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