The Wayback Machine - https://web.archive.org/web/20220202193212/https://www.geeksforgeeks.org/longest-increasing-consecutive-subsequence-set-2/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Longest Increasing consecutive subsequence | Set-2

  • Last Updated : 02 Feb, 2022

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: arr[] = {6, 7, 8, 3, 4, 5, 9, 10} 
Output: 5 

Approach: The naive and the dynamic programming approach has already been discussed in this article. This article discusses a simpler and easy to implement approach using Hashing. The idea is to store the length of subsequence ending with the current integer X in an unordered map m. Hence, if X + 1 occurs during the traversal, the length of the subsequence will be m[X] + 1. The maximum value in the map m is the required answer. 

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the longest
// increasing consecutive subsequence
int longestSubsequence(int arr[], int N)
{
    // Stores the length of longest
    // subsequence qnding with key
    unordered_map<int, int> m;
  
    // Stores the required answer
    int ans = 0;
  
    // Loop to traverse array
    for (int i = 0; i < N; i++) {
        // Length of subsequence
        // ending with arr[i]
        m[arr[i]] = max(m[arr[i]],
                        m[arr[i] - 1] + 1);
  
        // Update Answer
        ans = max(ans, m[arr[i]]);
    }
  
    // Return Answer
    return ans;
}
  
// Driver Code
int main()
{
    int arr[] = { 3, 4, 2, 6, 5, 3, 7, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    cout << longestSubsequence(arr, N);
  
    return 0;
}
Output
4

Time Complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!