Created
August 31, 2019 15:39
-
-
Save bachiri/747f5c3326d255a53304caf37010e98c to your computer and use it in GitHub Desktop.
Length of the largest subarray with contiguous elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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