How to find the maximum distance between two occurrences of same number in array with C

1 Answer

0 votes
#include <stdio.h>
#include <math.h>

int GetMaxDistance(int arr[], int size) {
    int maximumDistance = 0;
    for (int i = 0; i < size - 1; i++)
        for (int j = i + 1; j < size; j++)
            if (arr[i] == arr[j]) {
                int temp = abs(j - i);
                maximumDistance = maximumDistance > temp ? maximumDistance : temp;
            }
    return maximumDistance;
}

int main() {
    int arr[] = { 7, 1, 4, 3, 1, 5, 3, 4, 9, 1, 3 };
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("%d", GetMaxDistance(arr, size));

    return 0;
}




/*
run:
    
8
    
*/

 



answered Dec 17, 2022 by avibootz
...