From 595992b77a9d53cedc097d3318744be94e1a98c0 Mon Sep 17 00:00:00 2001 From: Aayush Date: Tue, 15 Jun 2021 00:19:11 +0530 Subject: [PATCH] chore(java): add longest consecutive subsequence (#356) --- algorithms/Java/README.md | 2 + .../longest-consecutive-subsequence.java | 87 +++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 algorithms/Java/arrays/longest-consecutive-subsequence.java diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 51294f90..9f71e23e 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -7,6 +7,7 @@ 3. [Left Rotation](arrays/left-rotation.java) 4. [Unique Digits of Large Number](arrays/unique-digits-of-large-number.java) 5. [Majority Element](arrays/majority-element.java) +6. [Longest Consecutive Subsequence](arrays/longest-consecutive-subsequence.java) ## Graphs @@ -22,6 +23,7 @@ 6. [Fold Linked List](linked-lists/fold-linked-list.java) ## Maths + 1. [Factorial](Maths/factorial_using_big_integer.java) ## Queues diff --git a/algorithms/Java/arrays/longest-consecutive-subsequence.java b/algorithms/Java/arrays/longest-consecutive-subsequence.java new file mode 100644 index 00000000..50872873 --- /dev/null +++ b/algorithms/Java/arrays/longest-consecutive-subsequence.java @@ -0,0 +1,87 @@ +/* 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. */ + +/* Time Complexity: O(n) + Space Complexity: O(n) */ + +import java.math.*; +import java.util.*; +import java.io.*; + +class Driverclass { + static class FastReader{ + BufferedReader br; + StringTokenizer st; + + public FastReader(){ + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next(){ + while (st == null || !st.hasMoreElements()){ + try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } + } + return st.nextToken(); + } + + String nextLine(){ + String str = ""; + try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } + return str; + } + + Integer nextInt(){ + return Integer.parseInt(next()); + } + } + + public static void main(String args[]) { + FastReader sc = new FastReader(); + PrintWriter out = new PrintWriter(System.out); + int t = sc.nextInt(); + + while(t>0) { + int n = sc.nextInt(); + int a[] = new int[n]; + + for(int i=0; i set = new HashSet<>(); + int ans=0; + for(int num: arr) + set.add(num); + for(int i=0; i