# Maximum distance between two occurrences of same element in array in C

CServer Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

We are given with an array of integers. The array has multiple occurrences of the same elements. The task here is to find the maximum distance between any two same elements of the array. We will pick each element from the array starting from the left. Then we will find the last occurrence of that same number and store the difference between indexes. Now if this difference is maximum then return it.

Input

Arr[] = { 1,2,4,1,3,4,2,5,6,5 }

Output −Maximum distance between two occurrences of same element in array − 4

Explanation − The repeating numbers with indexes −

1. 1, first index 0, last index 3 distance=3-0-1=2
2. 2, first index 1, last index 6 distance=6-1-1=4
3. 5, first index 7, last index 9 distance=9-7-1=1
Maximum distance between two occurrences of same element : 4

Input

Arr[] = { 10,20,1,10,10,21,12,0 }

Output −Maximum distance between two occurrences of same element in array − 3

Explanation − The repeating numbers with indexes −

1. 10 first index 0, last index 4 distance=4-0-1=3
Maximum distance between two occurrences of same element : 3

Note − if the input array has no repeating number, then return -1

## Approach used in the below program is as follows

• We take an integer array having repeating numbers as Arr[]

• The function maxDistance( int arr[],int n) is used to calculate the Maximum distance between two occurrences of the same element.

• We initialize the variable maxD with -1.

• Inside the for loop traverse the array of integers from the beginning.

• In nested for loop traverse the remaining elements and search for repetitions if any. ( if ( arr[i] == arr[j] ).

• If it is true then calculate the difference between numbers by subtracting the indexes. ( temp=j-i-1)

• If this value is maximum found so far, then store it in maxD

• Return maxD after traversing the whole array.

## Example

Live Demo

#include <stdio.h>
#include <math.h>
int maxDistance(int arr[],int n){
int size = n;
int maxD = -1;
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] == arr[j]){
int temp=abs(j-i-1);
maxD = maxD>temp?maxD:temp;
}
return maxD;
}
// Driver code
int main(){
int Arr[] = {1,2,4,1,3,4,2,5,6,5};
printf("Maximum distance between two occurrences of same element in array:%d", maxDistance(Arr,10) );
return 0;
}

## Output

If we run the above code it will generate the following output −

Maximum distance between two occurrences of same element in array − 4
Updated on 14-Aug-2020 08:05:48