Maximum distance between two occurrences of same element in array in Java

Hello friends, today we are going to see the implementation of maximum distance between two occurrences of the same element in the array in Java. Firstly, we will see an algorithm to demonstrate the approach to solving this problem.

Algorithm

  • Start
  • All the necessary elements are taken from the user.
  • Initialize the count variable to count the last position of the required element in the array.
  • Use of two loops, firstly, for the starting index and secondly, to find the last index and assign it to the count variable.
  • Find the maximum difference between the elements.
  • Print the max difference value.
  • End

Code

import java.util.*;
public class Max {
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of elements");
        int n = in.nextInt();
        int a[]=new int[n];
        System.out.println("Enter all the elements");
        for(int i=0;i<n;i++){
            a[i]=in.nextInt();
        }
        int count=-1;
        int max=Integer.MIN_VALUE;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(a[i]==a[j]){
                    count=j;
                }
                max=Math.max(max, count-i);
                
            }
        }
        System.out.println("Maximum distance "+max);       
    }
}

 

Output

Enter the number of elements
6
Enter all the elements
7 1 3 4 1 7
Maximum distance 5

Also read: How to find second largest number in an array in Java

Leave a Reply