📌  相关文章
📜  最长子序列使得相邻之间的差异为 1 | 2套

📅  最后修改于: 2021-10-27 16:59:57             🧑  作者: Mango

给定一个大小为n的数组。任务是找到最长的子序列,使得相邻子序列之间的差异为 1。需要 O(n) 的时间复杂度。
例子:

Input :  arr[] = {10, 9, 4, 5, 4, 8, 6}
Output :  3
As longest subsequences with difference 1 are, "10, 9, 8", 
"4, 5, 4" and "4, 5, 6".

Input :  arr[] = {1, 2, 3, 2, 3, 7, 2, 1}
Output :  7
As longest consecutive sequence is "1, 2, 3, 2, 3, 2, 1".

方法 1:以前在这篇文章中讨论过一种时间复杂度为 O(n 2 ) 的方法。
方法 2(高效方法):想法是创建一个具有(ele, len)形式的元组的哈希映射,其中len表示以元素ele结尾的最长子序列的长度。现在,对于每个元素 arr[i] 我们可以在哈希表中找到值 arr[i]-1 和 arr[i]+1 的长度,并考虑其中的最大值。将此最大值设为max 。现在,以 arr[i] 结尾的最长子序列的长度将是max+1 。更新此长度以及哈希表中的元素 arr[i]。最后,哈希表中具有最大长度的元素给出最长长度的子序列。

C++
// C++ implementation to find longest subsequence
// such that difference between adjacents is one
#include 
using namespace std;
   
// function to find longest subsequence such
// that difference between adjacents is one
int longLenSub(int arr[], int n)
{
    // hash table to map the array element with the
    // length of the longest subsequence of which
    // it is a part of and is the last element of
    // that subsequence
    unordered_map um;
      
    // to store the longest length subsequence
    int longLen = 0;
      
    // traverse the array elements
    for (int i=0; iJava
// Java implementation to find longest subsequence
// such that difference between adjacents is one
import java.util.*;
 
class GFG
{
     
// function to find longest subsequence such
// that difference between adjacents is one
static int longLenSub(int []arr, int n)
{
    // hash table to map the array element with the
    // length of the longest subsequence of which
    // it is a part of and is the last element of
    // that subsequence
    HashMap um = new HashMap();
     
    // to store the longest length subsequence
    int longLen = 0;
     
    // traverse the array elements
    for (int i = 0; i < n; i++)
    {
        // initialize current length
        // for element arr[i] as 0
        int len = 0;
         
        // if 'arr[i]-1' is in 'um' and its length
        // of subsequence is greater than 'len'
        if (um.containsKey(arr[i] - 1) &&
              len < um.get(arr[i] - 1))
              len = um.get(arr[i] - 1);
         
        // if 'arr[i]+1' is in 'um' and its length
        // of subsequence is greater than 'len'    
        if (um.containsKey(arr[i] + 1) &&
              len < um.get(arr[i] + 1))
              len = um.get(arr[i] + 1);
         
        // update arr[i] subsequence length in 'um'
        um. put(arr[i], len + 1);
         
        // update longest length
        if (longLen < um.get(arr[i]))
            longLen = um.get(arr[i]);
    }
         
    // required longest length subsequence
    return longLen;    
}
     
// Driver Code
public static void main(String[] args)
{
    int[] arr = {1, 2, 3, 4, 5, 3, 2};
    int n = arr.length;
    System.out.println("Longest length subsequence = " +
                                    longLenSub(arr, n));
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 implementation to find longest
# subsequence such that difference between
# adjacents is one
from collections import defaultdict
 
# function to find longest subsequence such
# that difference between adjacents is one
def longLenSub(arr, n):
 
    # hash table to map the array element
    # with the length of the longest
    # subsequence of which it is a part of
    # and is the last element of that subsequence
    um = defaultdict(lambda:0)
    longLen = 0
    for i in range(n):
 
        # / initialize current length
        # for element arr[i] as 0
        len1 = 0
 
        # if 'arr[i]-1' is in 'um' and its length
        # of subsequence is greater than 'len'
        if (arr[i - 1] in um and
            len1 < um[arr[i] - 1]):
            len1 = um[arr[i] - 1]
 
        # f 'arr[i]+1' is in 'um' and its length
        # of subsequence is greater than 'len'    
        if (arr[i] + 1 in um and
            len1 < um[arr[i] + 1]):
            len1 = um[arr[i] + 1]
 
        # update arr[i] subsequence
        # length in 'um'    
        um[arr[i]] = len1 + 1
 
        # update longest length
        if longLen < um[arr[i]]:
            longLen = um[arr[i]]
 
    # required longest length
    # subsequence
    return longLen
 
# Driver code
arr = [1, 2, 3, 4, 5, 3, 2]
n = len(arr)
print("Longest length subsequence =",
                  longLenSub(arr, n))
 
# This code is contributed by Shrikant13


C#
// C# implementation to find longest subsequence
// such that difference between adjacents is one
using System;
using System.Collections.Generic;
 
class GFG
{
     
// function to find longest subsequence such
// that difference between adjacents is one
static int longLenSub(int []arr, int n)
{
    // hash table to map the array element with the
    // length of the longest subsequence of which
    // it is a part of and is the last element of
    // that subsequence
    Dictionary um = new Dictionary();
     
    // to store the longest length subsequence
    int longLen = 0;
     
    // traverse the array elements
    for (int i = 0; i < n; i++)
    {
        // initialize current length
        // for element arr[i] as 0
        int len = 0;
         
        // if 'arr[i]-1' is in 'um' and its length
        // of subsequence is greater than 'len'
        if (um.ContainsKey(arr[i] - 1) &&
            len < um[arr[i] - 1])
            len = um[arr[i] - 1];
         
        // if 'arr[i]+1' is in 'um' and its length
        // of subsequence is greater than 'len'    
        if (um.ContainsKey(arr[i] + 1) &&
            len < um[arr[i] + 1])
            len = um[arr[i] + 1];
         
        // update arr[i] subsequence length in 'um'
        um[arr[i]] = len + 1;
         
        // update longest length
        if (longLen < um[arr[i]])
            longLen = um[arr[i]];
    }
         
    // required longest length subsequence
    return longLen;    
}
     
// Driver program to test above
static void Main()
{
    int[] arr = {1, 2, 3, 4, 5, 3, 2};
    int n = arr.Length;
    Console.Write("Longest length subsequence = " +
                               longLenSub(arr, n));
}
}
 
// This code is contributed by Mohit Kumar


Javascript


输出:

Longest length subsequence = 6

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程