fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. Scanner sc = new Scanner(System.in);
  14. int n = sc.nextInt();
  15. int nums[] = new int[n];
  16. for(int i=0;i<n; i++){
  17. nums[i] = sc.nextInt();
  18. }
  19.  
  20. HashMap<Integer,Boolean> hmap = new HashMap<>();
  21.  
  22. for(int k: nums){
  23. hmap.put(k,true);
  24. }
  25. int longestConsecutiveSequence=0;
  26. for(int num : nums){
  27. if(hmap.containsKey(num-1))
  28. hmap.put(num,false);
  29. }
  30.  
  31. for(int num : nums){
  32.  
  33. if(hmap.get(num)==true){
  34. int start=num;
  35. int count=0;
  36. while(hmap.containsKey(start)){
  37. start++;
  38. count++;
  39. }
  40. if(count>longestConsecutiveSequence)
  41. longestConsecutiveSequence=count;
  42. }
  43. }
  44. System.out.println(longestConsecutiveSequence);
  45. }
  46. }
Success #stdin #stdout 0.12s 56628KB
stdin
10
0 3 7 2 5 8 4 6 0 1
stdout
9