fork download
  1.  
  2.  
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. bool linearSearch(vector<int>&a, int num) {
  8. int n = a.size(); //size of array
  9. for (int i = 0; i < n; i++) {
  10. if (a[i] == num)
  11. return true;
  12. }
  13. return false;
  14. }
  15. int longestSuccessiveElements(vector<int>&a) {
  16. int n = a.size(); //size of array
  17. int longest = 1;
  18. //pick a element and search for its
  19. //consecutive numbers:
  20. for (int i = 0; i < n; i++) {
  21. int x = a[i];
  22. int cnt = 1;
  23. //search for consecutive numbers
  24. //using linear search:
  25. while (linearSearch(a, x + 1) == true) {
  26. x += 1;
  27. cnt += 1;
  28. }
  29.  
  30. longest = max(longest, cnt);
  31. }
  32. return longest;
  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 5284KB
stdin
Standard input is empty
stdout
The longest consecutive sequence is 4