How to find the maximum distance between two numbers in an array with PHP

1 Answer

0 votes
/**
 * Finds the maximum distance between two values in an array.
 *
 * Distance is defined as the absolute difference
 * between the indices of the two values.
 *
 * @param array $numbers Input array.
 * @param int   $value1  First value to find.
 * @param int   $value2  Second value to find.
 *
 * @return int Maximum distance, or -1 if either value is not found.
 */
function maxDistanceBetweenValues(array $numbers, int $value1, int $value2): int
{
    $firstValue1 = -1;
    $lastValue1  = -1;

    $firstValue2 = -1;
    $lastValue2  = -1;

    // Find the first and last occurrence of both values.
    foreach ($numbers as $index => $value) {
        if ($value === $value1) {
            if ($firstValue1 === -1) {
                $firstValue1 = $index;
            }

            $lastValue1 = $index;
        }

        if ($value === $value2) {
            if ($firstValue2 === -1) {
                $firstValue2 = $index;
            }

            $lastValue2 = $index;
        }
    }

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

    // Check the extreme combinations.
    $distance1 = abs($firstValue1 - $lastValue2);
    $distance2 = abs($firstValue2 - $lastValue1);

    return max($distance1, $distance2);
}

// Example
$array = [2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3];

$result = maxDistanceBetweenValues($array, 3, 8);

echo "Maximum distance between 3 and 8: {$result}" . PHP_EOL;


/*
run:

Maximum distance between 3 and 8: 7

*/

 



answered Oct 22 by avibootz

Related questions

...