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 :



title-img


                            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

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →