Skip to content

Instantly share code, notes, and snippets.

@bachiri
Created August 31, 2019 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bachiri/747f5c3326d255a53304caf37010e98c to your computer and use it in GitHub Desktop.
Save bachiri/747f5c3326d255a53304caf37010e98c to your computer and use it in GitHub Desktop.
Length of the largest subarray with contiguous elements
public class LengthLargestSubArray {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5, 6, 10, 8, 7, 9};
System.out.println("Length of the largest subArray is " + lengthLargestSubArray(arr));
}
private static int lengthLargestSubArray(int[] arr) {
Arrays.sort(arr);
int counter = 0;
int maxCounter = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] == arr[i - 1] + 1) {
counter++;
maxCounter = Math.max(maxCounter, counter);
} else
counter = 0;
}
return ++maxCounter;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment