Longest Monotonically Increasing Subsequence Size (N log N): Simple implementation
Given an array of random numbers, find the longest monotonically increasing subsequence (LIS) in the array. If you want to understand the O(NlogN) approach, it’s explained very clearly here.
In this post, a simple and time-saving implementation of O(NlogN) approach using stl is discussed. Below is the code for LIS O(NlogN):
Implementation:
C++
#include<iostream>
#include<algorithm>
#include<set>
using namespace std;
int lis( int arr[], int N)
{
int i;
set< int > s;
set< int >::iterator k;
for (i=0; i<N; i++)
{
if (s.insert(arr[i]).second)
{
k = s.find(arr[i]);
k++;
if (k!=s.end()) s.erase(k);
}
}
return s.size();
}
int main()
{
int arr[] = {8, 9, 12, 10, 11};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << lis(arr, n)<< endl;
}
|
Java
import java.util.*;
import java.util.Set;
class GFG {
public static int lis( int [] arr, int N)
{
Set<Integer> s = new HashSet<>();
Iterator<Integer> k;
for ( int i = 0 ; i < N; i++)
{
if (s.add(arr[i]))
{
k = s.iterator();
while (k.hasNext() && k.next() < arr[i]);
if (k.hasNext())
s.remove(k.next());
}
}
return s.size();
}
public static void main(String[] args)
{
int [] arr = { 8 , 9 , 12 , 10 , 11 };
int n = arr.length;
System.out.println(lis(arr, n));
}
}
|
Python3
def lis(arr):
s = set ()
for i in range ( len (arr)):
if arr[i] not in s:
s.add(arr[i])
next_greater = [x for x in s if x > arr[i]]
if next_greater:
s.remove( min (next_greater))
return len (s)
arr = [ 8 , 9 , 12 , 10 , 11 ]
print (lis(arr))
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static int lis( int [] arr, int N)
{
SortedSet< int > s = new SortedSet< int >();
SortedSet< int >.Enumerator k;
for ( int i = 0; i < N; i++)
{
if (s.Add(arr[i]))
{
k = s.GetEnumerator();
while (k.MoveNext() && k.Current < arr[i]) ;
if (k.MoveNext())
s.Remove(k.Current);
}
}
return s.Count;
}
public static void Main(String[] args)
{
int [] arr = { 8, 9, 12, 10, 11 };
int n = arr.Length;
Console.WriteLine(lis(arr, n));
}
}
|
Javascript
function lis(arr) {
var s = new Set();
for ( var i = 0; i < arr.length; i++) {
if (!s.has(arr[i])) {
s.add(arr[i]);
var nextGreater = Array.from(s).filter(x => x > arr[i]);
if (nextGreater.length > 0) {
s. delete (Math.min(...nextGreater));
}
}
}
return s.size;
}
var arr = [8, 9, 12, 10, 11];
console.log(lis(arr));
|
Time Complexity: O(N log N)
Auxiliary Space: O(N)
Last Updated :
17 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...