Advertisement
mmayoub

School, 09.09.2017, Ex6, max sequence length

Sep 9th, 2017
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1.  
  2. public class Ex6 {
  3.     // Write a Java program to find the length of the longest consecutive
  4.     // elements sequence from a given unsorted array of integers.
  5.     // Sample array: [49, 1, 3, 200, 2, 4, 70, 5]
  6.     // The longest consecutive elements sequence is [1, 2, 3, 4, 5], therefore
  7.     // the program will return its length 5.
  8.  
  9.     public static void main(String[] args) {
  10.         int[] arr = { 49, 1, 3, 200, 2, 4, 70, 5 };
  11.  
  12.         int maxLength = 0;
  13.  
  14.         for (int i = 0; i < arr.length; i += 1) {
  15.             int length = chainLength(arr, arr[i]);
  16.             if (length > maxLength) {
  17.                 maxLength = length;
  18.             }
  19.         }
  20.  
  21.         System.out.println("Max chain length is " + maxLength);
  22.  
  23.     }
  24.  
  25.     // return true if n exists in array
  26.     public static boolean isFound(int[] arr, int n) {
  27.         for (int i = 0; i < arr.length; i += 1) {
  28.             if (arr[i] == n)
  29.                 return true;
  30.         }
  31.  
  32.         return false;
  33.     }
  34.  
  35.     // length of chain starting from start
  36.     public static int chainLength(int[] arr, int start) {
  37.         int length = 0;
  38.  
  39.         while (isFound(arr, start)) {
  40.             length += 1;
  41.             start += 1;
  42.         }
  43.  
  44.         return length;
  45.     }
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement