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. }
  14. }
  15.  
  16. class Solution {
  17. public int longestConsecutive(int[] nums) {
  18.  
  19.  
  20.  
  21. //present in scaler
  22.  
  23.  
  24. HashSet<Integer> completeSet = new HashSet<Integer>();
  25.  
  26.  
  27.  
  28. for(int i = 0 ; i<nums.length ; i++){ //creting the complete hashset first
  29.  
  30. int element = nums[i];
  31.  
  32. completeSet.add(element);
  33.  
  34. }
  35.  
  36.  
  37.  
  38. int max = 0;
  39.  
  40.  
  41.  
  42.  
  43. //now for each element n in the hashset if an element less than it exists then we do not need to calculate the subsequence for this element as the n-1th elements consequtive sequence willl always be greater than the current elements//
  44.  
  45.  
  46. for(Integer element : completeSet){
  47.  
  48. if(completeSet.contains((element-1))){
  49.  
  50. continue;
  51. }
  52.  
  53.  
  54. else{
  55.  
  56. int length = 1;
  57.  
  58. //otherwise calculate the series
  59.  
  60. int start = element +1;
  61.  
  62. while(completeSet.contains((start))){
  63.  
  64.  
  65. length++;
  66.  
  67. start++;
  68. }
  69.  
  70.  
  71.  
  72. if(max<length){
  73.  
  74.  
  75. max = length;
  76. }
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83. }
  84.  
  85.  
  86.  
  87.  
  88. }
  89.  
  90.  
  91. return max;
  92.  
  93.  
  94.  
  95.  
  96. }
  97. }
Success #stdin #stdout 0.09s 54636KB
stdin
Standard input is empty
stdout
Standard output is empty