Open In App

Longest Increasing consecutive subsequence

Last Updated : 08 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given N elements, write a program that prints the length of the longest increasing consecutive subsequence.

Examples: 

Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} 
Output :
Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. 

Input : a[] = {6, 7, 8, 3, 4, 5, 9, 10} 
Output :
Explanation: 6, 7, 8, 9, 10 is the longest increasing subsequence 

Naive Approach: For every element, find the length of the subsequence starting from that particular element. Print the longest length of the subsequence thus formed:

C++




#include <bits/stdc++.h>
using namespace std;
 
int LongestSubsequence(int a[], int n)
{
    int ans = 0;
   
      // Traverse every element to check if any
    // increasing subsequence starts from this index
    for(int i=0; i<n; i++)
    {
          // Initialize cnt variable as 1, which defines
        // the current length of the increasing subsequence
        int cnt = 1;
        for(int j=i+1; j<n; j++)
            if(a[j] == (a[i]+cnt)) cnt++;
         
      // Update the answer if the current length is
      // greater than already found length
        ans = max(ans, cnt);
    }
     
    return ans;
}
 
int main()
{
    int a[] = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << LongestSubsequence(a, n);
 
    return 0;
}


Java




import java.util.Scanner;
 
public class Main {
 
  public static int LongestSubsequence(int a[], int n)
  {
 
    int ans = 0;
   
      // Traverse every element to check if any
    // increasing subsequence starts from this index
    for(int i=0; i<n; i++)
    {
          // Initialize cnt variable as 1, which defines
        // the current length of the increasing subsequence
        int cnt = 1;
        for(int j=i+1; j<n; j++)
            if(a[j] == (a[i]+cnt)) cnt++;
         
      // Update the answer if the current length is
      // greater than already found length
        if(cnt > ans)
          ans = cnt;
    }
     
    return ans;
  }
  public static void main(String[] args) {
    int[] a = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12};
    int n = a.length;
    System.out.println(LongestSubsequence(a, n));
  }
}
 
// This code contributed by Ajax


Python3




def longest_subsequence(a, n):
    ans = 0
 
    # Traverse every element to check if any
    # increasing subsequence starts from this index
    for i in range(n):
        # Initialize cnt variable as 1, which defines
        # the current length of the increasing subsequence
        cnt = 1
        for j in range(i + 1, n):
            if a[j] == (a[i] + cnt):
                cnt += 1
 
        # Update the answer if the current length is
        # greater than the already found length
        ans = max(ans, cnt)
 
    return ans
 
if __name__ == "__main__":
    a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12]
    n = len(a)
    print(longest_subsequence(a, n))


C#




using System;
 
class GFG
{
    static int LongestSubsequence(int[] a, int n)
    {
        int ans = 0;
        // Traverse every element to check if any
        // increasing subsequence starts from this index
        for (int i = 0; i < n; i++)
        {
            // Initialize cnt variable as 1, which defines
            // current length of the increasing subsequence
            int cnt = 1;
            for (int j = i + 1; j < n; j++)
            {
                if (a[j] == (a[i] + cnt))
                {
                    cnt++;
                }
                // Update the answer if the current length is
                // greater than the already found length
                ans = Math.Max(ans, cnt);
            }
        }
        return ans;
    }
    static void Main()
    {
        int[] a = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 };
        int n = a.Length;
        Console.WriteLine(LongestSubsequence(a, n));
    }
}


Javascript




function LongestSubsequence(a, n)
{
    let ans = 0;
   
      // Traverse every element to check if any
    // increasing subsequence starts from this index
    for(let i=0; i<n; i++)
    {
          // Initialize cnt variable as 1, which defines
        // the current length of the increasing subsequence
        let cnt = 1;
        for(let j=i+1; j<n; j++)
            if(a[j] == (a[i]+cnt)) cnt++;
         
      // Update the answer if the current length is
      // greater than already found length
        ans = Math.max(ans, cnt);
    }
     
    return ans;
}
 
let a = [ 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 ];
let n = a.length;
console.log(LongestSubsequence(a, n));


Output

6

Time Complexity: O(N2)
Auxiliary Space: O(1)

Dynamic Programming Approach: Let DP[i] store the length of the longest subsequence which ends with A[i]. For every A[i], if A[i]-1 is present in the array before i-th index, then A[i] will add to the increasing subsequence which has A[i]-1. Hence, DP[i] = DP[ index(A[i]-1) ] + 1. If A[i]-1 is not present in the array before i-th index, then DP[i]=1 since the A[i] element forms a subsequence which starts with A[i]. Hence, the relation for DP[i] is: 

If A[i]-1 is present before i-th index:  

  • DP[i] = DP[ index(A[i]-1) ] + 1

else:

  • DP[i] = 1

Given below is the illustration of the above approach:  

C++




// CPP program to find length of the
// longest increasing subsequence
// whose adjacent element differ by 1
#include <bits/stdc++.h>
using namespace std;
 
// function that returns the length of the
// longest increasing subsequence
// whose adjacent element differ by 1
int longestSubsequence(int a[], int n)
{
    // stores the index of elements
    unordered_map<int, int> mp;
 
    // stores the length of the longest
    // subsequence that ends with a[i]
    int dp[n];
    memset(dp, 0, sizeof(dp));
 
    int maximum = INT_MIN;
 
    // iterate for all element
    for (int i = 0; i < n; i++) {
 
        // if a[i]-1 is present before i-th index
        if (mp.find(a[i] - 1) != mp.end()) {
 
            // last index of a[i]-1
            int lastIndex = mp[a[i] - 1] - 1;
 
            // relation
            dp[i] = 1 + dp[lastIndex];
        }
        else
            dp[i] = 1;
 
        // stores the index as 1-index as we need to
        // check for occurrence, hence 0-th index
        // will not be possible to check
        mp[a[i]] = i + 1;
 
        // stores the longest length
        maximum = max(maximum, dp[i]);
    }
 
    return maximum;
}
 
// Driver Code
int main()
{
    int a[] = { 4, 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << longestSubsequence(a, n);
    return 0;
}


Java




// Java program to find length of the
// longest increasing subsequence
// whose adjacent element differ by 1
 
import java.util.*;
class lics {
    static int LongIncrConseqSubseq(int arr[], int n)
    {
        // create hashmap to save latest consequent
        // number as "key" and its length as "value"
        HashMap<Integer, Integer> map = new HashMap<>();
        
        // put first element as "key" and its length as "value"
        map.put(arr[0], 1);
        for (int i = 1; i < n; i++) {
        
            // check if last consequent of arr[i] exist or not
            if (map.containsKey(arr[i] - 1)) {
        
                // put the updated consequent number
                // and increment its value(length)
                map.put(arr[i], map.get(arr[i] - 1) + 1);
           
                // remove the last consequent number
                map.remove(arr[i] - 1);
            }
 
            // if there is no last consequent of
            // arr[i] then put arr[i]
            else {
                map.put(arr[i], 1);
            }
        }
        return Collections.max(map.values());
    }
 
    // driver code
    public static void main(String args[])
    {
        // Take input from user
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int arr[] = new int[n];
        for (int i = 0; i < n; i++)
            arr[i] = sc.nextInt();
        System.out.println(LongIncrConseqSubseq(arr, n));
    }
}
// This code is contributed by CrappyDoctor


Python3




# python program to find length of the
# longest increasing subsequence
# whose adjacent element differ by 1
 
from collections import defaultdict
import sys
 
# function that returns the length of the
# longest increasing subsequence
# whose adjacent element differ by 1
 
def longestSubsequence(a, n):
    mp = defaultdict(lambda:0)
 
    # stores the length of the longest
    # subsequence that ends with a[i]
    dp = [0 for i in range(n)]
    maximum = -sys.maxsize
 
    # iterate for all element
    for i in range(n):
 
        # if a[i]-1 is present before i-th index
        if a[i] - 1 in mp:
 
            # last index of a[i]-1
            lastIndex = mp[a[i] - 1] - 1
 
            # relation
            dp[i] = 1 + dp[lastIndex]
        else:
            dp[i] = 1
 
            # stores the index as 1-index as we need to
            # check for occurrence, hence 0-th index
            # will not be possible to check
        mp[a[i]] = i + 1
 
        # stores the longest length
        maximum = max(maximum, dp[i])
    return maximum
 
 
# Driver Code
a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12]
n = len(a)
print(longestSubsequence(a, n))
 
# This code is contributed by Shrikant13


C#




// C# program to find length of the
// longest increasing subsequence
// whose adjacent element differ by 1
using System;
using System.Collections.Generic;
class GFG{
     
static int longIncrConseqSubseq(int []arr,
                                int n)
{
  // Create hashmap to save
  // latest consequent number
  // as "key" and its length
  // as "value"
  Dictionary<int,
             int> map = new Dictionary<int,
                                       int>();
 
  // Put first element as "key"
  // and its length as "value"
  map.Add(arr[0], 1);
  for (int i = 1; i < n; i++)
  {
    // Check if last consequent
    // of arr[i] exist or not
    if (map.ContainsKey(arr[i] - 1))
    {
      // put the updated consequent number
      // and increment its value(length)
      map.Add(arr[i], map[arr[i] - 1] + 1);
 
      // Remove the last consequent number
      map.Remove(arr[i] - 1);
    }
 
    // If there is no last consequent of
    // arr[i] then put arr[i]
    else
    {
      if(!map.ContainsKey(arr[i]))
        map.Add(arr[i], 1);
    }
  }
   
  int max = int.MinValue;
  foreach(KeyValuePair<int,
                       int> entry in map)
  {
    if(entry.Value > max)
    {
      max = entry.Value;
    }
  }
  return max;
}
 
// Driver code
public static void Main(String []args)
{
  // Take input from user
  int []arr = {3, 10, 3, 11,
               4, 5, 6, 7, 8, 12};
  int n = arr.Length;
  Console.WriteLine(longIncrConseqSubseq(arr, n));
}
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
 
// JavaScript program to find length of the
// longest increasing subsequence
// whose adjacent element differ by 1
 
// function that returns the length of the
// longest increasing subsequence
// whose adjacent element differ by 1
function longestSubsequence(a, n)
{
    // stores the index of elements
    var mp = new Map();
 
    // stores the length of the longest
    // subsequence that ends with a[i]
    var dp = Array(n).fill(0);
 
    var maximum = -1000000000;
 
    // iterate for all element
    for (var i = 0; i < n; i++) {
 
        // if a[i]-1 is present before i-th index
        if (mp.has(a[i] - 1)) {
 
            // last index of a[i]-1
            var lastIndex = mp.get(a[i] - 1) - 1;
 
            // relation
            dp[i] = 1 + dp[lastIndex];
        }
        else
            dp[i] = 1;
 
        // stores the index as 1-index as we need to
        // check for occurrence, hence 0-th index
        // will not be possible to check
        mp.set(a[i], i + 1);
 
        // stores the longest length
        maximum = Math.max(maximum, dp[i]);
    }
 
    return maximum;
}
 
// Driver Code
var a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12];
var n = a.length;
document.write( longestSubsequence(a, n));
 
</script>


Output

6







Complexity Analysis:

  • Time Complexity: O(N), as we are using a loop to traverse N times.
  • Auxiliary Space: O(N), as we are using extra space for dp and map m.


Previous Article
Next Article

Similar Reads

Longest Increasing Subsequence using Longest Common Subsequence Algorithm
Given an array arr[] of N integers, the task is to find and print the Longest Increasing Subsequence.Examples: Input: arr[] = {12, 34, 1, 5, 40, 80} Output: 4 {12, 34, 40, 80} and {1, 5, 40, 80} are the longest increasing subsequences.Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80} Output: 6 Prerequisite: LCS, LISApproach: The longest increasing
12 min read
Printing longest Increasing consecutive subsequence
Given n elements, write a program that prints the longest increasing subsequence whose adjacent element difference is one. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 3 4 5 6 7 8 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6, 7, 8, 3, 4, 5, 9, 10} O
8 min read
Longest Increasing consecutive subsequence | Set-2
Given an array arr[] of N elements, the task is to find the length of the longest increasing subsequence whose adjacent element difference is one. Examples: Input: arr[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output: 6 Explanation: The subsequence {3, 4, 5, 6, 7, 8} is the longest increasing subsequence whose adjacent elements differs by one. Input: a
5 min read
Largest increasing subsequence of consecutive integers
Given an array of n positive integers. We need to find the largest increasing sequence of consecutive positive integers. Examples: Input : arr[] = {5, 7, 6, 7, 8} Output : Size of LIS = 4 LIS = 5, 6, 7, 8 Input : arr[] = {5, 7, 8, 7, 5} Output : Size of LIS = 2 LIS = 7, 8 This problem can be solved easily by the concept of LIS where each next great
6 min read
Print the longest increasing consecutive subarray
Given an array arr[] of size N, the task is to print the longest increasing subarray such that elements in the subarray are consecutive integers. Examples: Input: arr[] = {1, 9, 3, 4, 20, 2}Output: {3, 4}Explanation: The subarray {3, 4} is the longest subarray of consecutive elements Input: arr[] = {36, 41, 56, 32, 33, 34, 35, 43, 32, 42}Output: {3
5 min read
Find the length of Longest increasing Consecutive Subarray
Given an array arr[] of N integers, the task is to find the length of the longest increasing subarray such that elements in the subarray are consecutive integers. Examples: Input: arr[] = {1, 9, 3, 4, 20, 2}Output: 2Explanation: The subarray {3, 4} is the longest subarray of consecutive elements Input: arr[] = {36, 41, 56, 32, 33, 34, 35, 43, 32, 4
4 min read
Construction of Longest Increasing Subsequence (N log N)
In my previous post, I have explained about longest increasing sub-sequence (LIS) problem in detail. However, the post only covered code related to querying size of LIS, but not the construction of LIS. I left it as an exercise. If you have solved, cheers. If not, you are not alone, here is code. If you have not read my previous post, read here. No
10 min read
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/C++ Co
5 min read
C/C++ Program for Longest Increasing Subsequence
Given an array arr[] of size N, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order. Examples: Input: arr[] = {3, 10, 2, 1, 20}Output: 3Explanation: The longest increasing subsequence is 3, 10, 20 Input: arr[] = {3,
8 min read
C++ Program for Longest Increasing Subsequence
The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. Examples: Input : arr[] = {3, 10, 2, 1, 20} O
9 min read