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

1 Answer

0 votes
using System;

public static class DistanceFinder
{
    /// <summary>
    /// Finds the maximum distance between two values in an array.
    /// Distance is defined as the absolute difference between indices.
    /// </summary>
    /// <param name="numbers">Input array.</param>
    /// <param name="value1">First value to search for.</param>
    /// <param name="value2">Second value to search for.</param>
    /// <returns>
    /// Maximum distance if both values exist; otherwise -1.
    /// </returns>
    public static int MaxDistanceBetweenValues(
        int[] numbers,
        int value1,
        int value2)
    {
        int firstValue1 = -1;
        int lastValue1 = -1;

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

        // Find the first and last occurrence of both values.
        for (int i = 0; i < numbers.Length; i++)
        {
            if (numbers[i] == value1) {
                if (firstValue1 == -1) {
                    firstValue1 = i;
                }

                lastValue1 = i;
            }

            if (numbers[i] == value2) {
                if (firstValue2 == -1) {
                    firstValue2 = i;
                }

                lastValue2 = i;
            }
        }

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

        // The maximum distance must involve extreme occurrences.
        int distance1 = Math.Abs(firstValue1 - lastValue2);
        int distance2 = Math.Abs(firstValue2 - lastValue1);

        return Math.Max(distance1, distance2);
    }

    public static void Main()
    {
        int[] numbers =
        {
            2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3
        };

        int distance = MaxDistanceBetweenValues(numbers, 3, 8);

        Console.WriteLine($"Maximum distance between 3 and 8: {distance}");
    }
}


/*
run:

Maximum distance between 3 and 8: 7

*/

 



answered Oct 22 by avibootz

Related questions

...