fork download
  1. /* Java program to find length of the largest subarray which has
  2. all contiguous elements */
  3. import java.util.*;
  4.  
  5. class Main
  6. {
  7. // This function prints all distinct elements
  8. static int findLength(int arr[])
  9. {
  10. int n = arr.length;
  11. int max_len = 1; // Initialize result
  12.  
  13. // One by one fix the starting points
  14. for (int i=0; i<n-1; i++)
  15. {
  16. // Create an empty hash set and add i'th element
  17. // to it.
  18. HashSet<Integer> set = new HashSet<>();
  19. set.add(arr[i]);
  20.  
  21. // Initialize max and min in current subarray
  22. int mn = arr[i], mx = arr[i];
  23.  
  24. // One by one fix ending points
  25. for (int j=i+1; j<n; j++)
  26. {
  27. // If current element is already in hash set, then
  28. // this subarray cannot contain contiguous elements
  29. if (set.contains(arr[j]))
  30. break;
  31.  
  32. // Else add current element to hash set and update
  33. // min, max if required.
  34. set.add(arr[j]);
  35. mn = Math.min(mn, arr[j]);
  36. mx = Math.max(mx, arr[j]);
  37.  
  38. // We have already checked for duplicates, now check
  39. // for other property and update max_len if needed
  40. if (mx-mn == j-i)
  41. max_len = Math.max(max_len, mx-mn+1);
  42. }
  43. }
  44. return max_len; // Return result
  45. }
  46.  
  47. // Driver method to test above method
  48. public static void main (String[] args)
  49. {
  50. int arr[] = {2,4,1,6,3,7,8,7};
  51. System.out.println("Length of the longest contiguous subarray is " +
  52. findLength(arr));
  53. }
  54. }
  55.  
Success #stdin #stdout 0.09s 48392KB
stdin
Standard input is empty
stdout
Length of the longest contiguous subarray is 2