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

1 Answer

0 votes
#include <stdio.h>
#include <stddef.h> // size_t
#include <stdlib.h> // abs

/**
 * Finds the maximum distance between two target values in an array.
 *
 * Distance = absolute difference between indices.
 *
 * Returns:
 *   - Maximum distance if both values exist.
 *   - -1 if either value is not found.
 */
int max_distance_between_values(const int arr[],
                                size_t size,
                                int value1,
                                int value2)
{
    int first1 = -1;
    int last1  = -1;

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

    for (size_t i = 0; i < size; ++i)
    {
        if (arr[i] == value1) {
            if (first1 == -1) {
                first1 = (int)i;
            }
            last1 = (int)i;
        }

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

    /* One or both values were not found */
    if (first1 == -1 || first2 == -1) {
        return -1;
    }

    /* Check both extreme combinations */
    int distance1 = abs(first1 - last2);
    int distance2 = abs(first2 - last1);

    return (distance1 > distance2) ? distance1 : distance2;
}

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

    size_t size = sizeof(arr) / sizeof(arr[0]);

    int result = max_distance_between_values(arr, size, 3, 8);

    printf("Maximum distance between 3 and 8: %d\n", result);

    return 0;
}


/*
run:

Maximum distance between 3 and 8: 7

*/

 



answered Oct 22 by avibootz

Related questions

...