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

1 Answer

0 votes
public class MaxDistanceFinder {

    /**
     * Finds the maximum distance between two values in an array.
     *
     * Distance = abs(indexA - indexB)
     *
     * @param arr    Input array
     * @param value1 First value to search for
     * @param value2 Second value to search for
     * @return Maximum distance, or -1 if either value is not found
     */
    public static int maxDistanceBetweenValues(int[] arr,
                                               int value1,
                                               int value2) {

        int first1 = -1;
        int last1 = -1;

        int first2 = -1;
        int last2 = -1;

        // Find the first and last occurrence of both values
        for (int i = 0; i < arr.length; i++) {

            if (arr[i] == value1) {
                if (first1 == -1) {
                    first1 = i;
                }
                last1 = i;
            }

            if (arr[i] == value2) {
                if (first2 == -1) {
                    first2 = i;
                }
                last2 = i;
            }
        }

        // One or both values do not exist
        if (first1 == -1 || first2 == -1) {
            return -1;
        }

        // Check the two extreme combinations
        int distance1 = Math.abs(first1 - last2);
        int distance2 = Math.abs(first2 - last1);

        return Math.max(distance1, distance2);
    }

    public static void main(String[] args) {

        int[] arr = {
            2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3
        };

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

        System.out.println("Maximum distance between 3 and 8: " + result);
    }
}


/*
run:

Maximum distance between 3 and 8: 7

*/

 



answered Oct 22 by avibootz

Related questions

...