How to find the maximum distance between two numbers in a vector with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>

/**
 * Returns the maximum distance between two target values in a vector.
 *
 * Distance is defined as:
 *     abs(indexA - indexB)
 *
 * If one or both values do not exist in the vector,
 * the function returns -1.
 */
int maxDistanceBetweenValues(const std::vector<int>& nums,
                             int value1,
                             int value2)
{
    int firstValue1 = -1;
    int lastValue1  = -1;

    int firstValue2 = -1;
    int lastValue2  = -1;

    for (size_t i = 0; i < nums.size(); ++i)
    {
        if (nums[i] == value1) {
            if (firstValue1 == -1)
                firstValue1 = static_cast<int>(i);

            lastValue1 = static_cast<int>(i);
        }

        if (nums[i] == value2) {
            if (firstValue2 == -1)
                firstValue2 = static_cast<int>(i);

            lastValue2 = static_cast<int>(i);
        }
    }

    // One or both values were not found.
    if (firstValue1 == -1 || firstValue2 == -1)
        return -1;

    return std::max(
        std::abs(firstValue1 - lastValue2),
        std::abs(firstValue2 - lastValue1)
    );
}

int main()
{
    std::vector<int> vec = {
        2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3
    };

    int result = maxDistanceBetweenValues(vec, 3, 8);

    std::cout << "Maximum distance: " << result << '\n';
}


/*
run:

Maximum distance: 7

*/

 



answered Oct 22 by avibootz
edited Oct 22 by avibootz
...