Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Ex6 {
- // Write a Java program to find the length of the longest consecutive
- // elements sequence from a given unsorted array of integers.
- // Sample array: [49, 1, 3, 200, 2, 4, 70, 5]
- // The longest consecutive elements sequence is [1, 2, 3, 4, 5], therefore
- // the program will return its length 5.
- public static void main(String[] args) {
- int[] arr = { 49, 1, 3, 200, 2, 4, 70, 5 };
- int maxLength = 0;
- for (int i = 0; i < arr.length; i += 1) {
- int length = chainLength(arr, arr[i]);
- if (length > maxLength) {
- maxLength = length;
- }
- }
- System.out.println("Max chain length is " + maxLength);
- }
- // return true if n exists in array
- public static boolean isFound(int[] arr, int n) {
- for (int i = 0; i < arr.length; i += 1) {
- if (arr[i] == n)
- return true;
- }
- return false;
- }
- // length of chain starting from start
- public static int chainLength(int[] arr, int start) {
- int length = 0;
- while (isFound(arr, start)) {
- length += 1;
- start += 1;
- }
- return length;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement