fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int longestConsecutive(vector<int>& nums) {
  6.  
  7. unordered_set<int> s(nums.begin(), nums.end());
  8.  
  9. if (nums.size() == 0) {
  10. return 0;
  11. }
  12.  
  13. int longest = 1;
  14.  
  15. for (auto it : s) {
  16. if (s.find(it - 1) == s.end()) {
  17. int cnt = 1;
  18. int x = it;
  19.  
  20. while (s.find(x + 1) != s.end()) {
  21. cnt++;
  22. x = x + 1;
  23. }
  24.  
  25. longest = max(longest, cnt);
  26. }
  27. }
  28.  
  29. return longest;
  30. }
  31.  
  32. int main() {
  33. int n;
  34. cin >> n;
  35.  
  36. vector<int> nums(n);
  37.  
  38. for (int i = 0; i < n; i++) {
  39. cin >> nums[i];
  40. }
  41.  
  42. cout << longestConsecutive(nums);
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 5320KB
stdin
6
100 4 200 1 3 2
stdout
4