Skip to content

Added the solution for Longest consecutive subsequence from gfg #267

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions C++/Longest Subs.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// 450dsa q24 : Given an array of positive integers. Find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.

#include <bits/stdc++.h>
using namespace std;

int longest_consecutive_subarray(int arr[], int n)
{
unordered_set<int> s;
for (int i = 0; i < n; i++)
{
s.insert(arr[i]);
}
int ans = 0;
for (auto i = s.begin(); i != s.end(); i++)
{
if (s.find(*i - 1) == s.end())
{
int num = *i;
int count = 0;
while (s.find(num) != s.end())
{
count++;
num++;
}
ans = max(ans, count);
}
}
return ans;
}

int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << longest_consecutive_subarray(arr, n);
return 0;
}