fork download
  1. import java.util.*;
  2. // Brute-force max distance between two occurance of same element
  3. class Ideone {
  4. public static int maxDistance(int[] arr) {
  5. int maxDist = 0;
  6. int n = arr.length;
  7. for (int i = 0; i < n; i++) {
  8. for (int j = i + 1; j < n; j++) {
  9. if (arr[i] == arr[j]) {
  10. int dist = j - i;
  11. if (dist > maxDist) {
  12. maxDist = dist;
  13. }
  14. }
  15. }
  16. }
  17.  
  18. return maxDist;
  19. }
  20.  
  21. public static void main(String[] args) throws java.lang.Exception {
  22. int[ ] arr = {1, 1, 2, 2, 2, 1};
  23. System.out.println("Max Distance: " + maxDistance(arr));
  24.  
  25. }
  26. }
  27.  
Success #stdin #stdout 0.16s 55720KB
stdin
Standard input is empty
stdout
Max Distance: 5