fork download
  1.  
  2.  
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. int longestSuccessiveElements(vector<int>&a) {
  8. int n = a.size();
  9. if (n == 0) return 0;
  10.  
  11. //sort the array:
  12. sort(a.begin(), a.end());
  13. int lastSmaller = INT_MIN;
  14. int cnt = 0;
  15. int longest = 1;
  16.  
  17. //find longest sequence:
  18. for (int i = 0; i < n; i++) {
  19. if (a[i] - 1 == lastSmaller) {
  20. //a[i] is the next element of the
  21. //current sequence.
  22. cnt += 1;
  23. lastSmaller = a[i];
  24. }
  25. else if (a[i] != lastSmaller) {
  26. cnt = 1;
  27. lastSmaller = a[i];
  28. }
  29. longest = max(longest, cnt);
  30. }
  31. return longest;
  32.  
  33. }
  34.  
  35. int main()
  36. {
  37. vector<int> a = {100, 200, 1, 2, 3, 4};
  38. int ans = longestSuccessiveElements(a);
  39. cout << "The longest consecutive sequence is " << ans << "\n";
  40. return 0;
  41. }
  42.  
  43.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
The longest consecutive sequence is 4