The Longest Increasing Subsequence
Problem Statement :
An Introduction to the Longest Increasing Subsequence Problem The task is to find the length of the longest subsequence in a given array of integers such that all elements of the subsequence are sorted in strictly ascending order. This is called the Longest Increasing Subsequence (LIS) problem. For example, the length of the LIS for [15,27,14,38,26,55,46,65,85] is 6 since the longest increasing subsequence is [15,27,38,55,65,85]. Here's a great YouTube video of a lecture from MIT's Open-CourseWare covering the topic. This is one approach which solves this in quadratic time using dynamic programming. A more efficient algorithm which solves the problem in O(n log n) time is available here. Given a sequence of integers, find the length of its longest strictly increasing subsequence. Function Description Complete the longestIncreasingSubsequence function in the editor below. It should return an integer that denotes the array's LIS. longestIncreasingSubsequence has the following parameter(s): arr: an unordered array of integers Input Format The first line contains a single integer n, the number of elements in arr. Each of the next n lines contains an integer, arr[i] Constraints 1 <= n <= 10^6 1 <= arr[i] <= 10^5 Output Format Print a single line containing a single integer denoting the length of the longest increasing subsequence.
Solution :
Solution in C :
In C++ :
#include <iostream>
#include <cmath>
#include <algorithm>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <ctime>
using namespace std;
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define forit(s) for(__typeof(s.begin()) it = s.begin(); it != s.end(); it ++)
#define N 1000100
#define all(a) a.begin(), a.end()
#define ll long long
#define pii pair <int, int>
#define sz(a) (int)a.size()
#define vi vector <int>
#define forn(i, n) for(int i = 0; i < n; i ++)
const int inf = (int)(1e9);
const int mod = inf + 7;
const double pi = acos(-1.0);
const double eps = 1e-9;
int n, a[N];
int main () {
#ifdef LOCAL
freopen("a.in", "r", stdin);
freopen("a.out", "w", stdout);
#endif
cin >> n;
for(int i = 0; i < n; i++) scanf("%d", a + i);
vector <int> d(N, 0);
d[0] = -inf;
for(int i = 1; i < N; i++) d[i] = inf;
for(int i = 0; i < n; i++) {
int j = upper_bound(all(d), a[i]) - d.begin();
if(d[j - 1] < a[i] && a[i] < d[j]) d[j] = a[i];
}
for(int i = N - 1;; i--) {
if(d[i] != inf) {
cout << i;
return 0;
}
}
return 0;
}
In Java :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
int[] array = new int[n];
for(int i = 0 ; i < n; i++ )
{
array[i] = reader.nextInt();
}
System.out.println(getLengthOfLIS(array));
}
public static int getLengthOfLIS(int[] array)
{
TreeSet<Integer> s = new TreeSet<Integer>();
for( int i = 0 ; i < array.length ; i++)
{
//if array[i] is newly added?
if( s.add(array[i]) )
{
//if array[i] is not the last element?
if( array[i] != s.last() )
{
//remove it's next element; s.higher() gives the least element
//which is greater than array[i]
s.remove(s.higher(array[i]));
}
}
}
return s.size();
}
}
In C :
#include <stdio.h>
int n,a[1000000],b[1000000];
int getRight(int *Arr,int left,int right,int value)
{
int mid;
while(right>left+1)
{
mid=left+(right-left)/2;
if(Arr[mid]>=value)right=mid;
else left=mid;
}
return right;
}
int CalcLIS()
{
int i,res=1;
b[0]=a[0];
for(i=1;i<n;i++)
{
if(a[i]<b[0])
b[0]=a[i];
else if(a[i]>b[res-1])
b[res++]=a[i];
else
b[getRight(b,-1,res-1,a[i])]=a[i];
}
return res;
}
int main()
{
int i;
scanf("%d",&n);
for(i=0;i<n;i++)scanf("%d",&a[i]);
printf("%d",CalcLIS());
return 0;
}
In Python3 :
import bisect
N = int(input())
A = [int(input()) for c in range(N)]
P = [0] * N
M = [0] * (N + 1)
L = 0
for i in range(N):
lo, hi = 1, L
while lo <= hi:
mid = lo + (hi-lo) // 2
if A[M[mid]] < A[i]:
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if newL > L:
L = newL
print(L)
View More Similar Problems
Components in a graph
There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu
View Solution →Kundu and Tree
Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that
View Solution →Super Maximum Cost Queries
Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and
View Solution →Contacts
We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co
View Solution →No Prefix Set
There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio
View Solution →Cube Summation
You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor
View Solution →