📌  相关文章
📜  最长的非递减子序列的长度,以使相邻元素之间的差异最大为1

📅  最后修改于: 2021-04-17 17:30:53             🧑  作者: Mango

给定一个由N个整数组成的数组arr [] ,任务是找到最长的非递减子序列的长度,以使相邻元素之间的差最大为1

例子:

方法:按照以下步骤解决问题:

  • 以递增顺序对数组arr []进行排序。
  • 初始化一个变量,例如maxLen = 1,以存储子序列的最大可能长度。初始化另一个变量,例如len = 1,以存储每个子序列的当前长度。
  • 用指针i和每个元素遍历数组arr []
    • 检查abs(arr [i] – arr [i – 1])是否≤1 。如果发现为真,则将len1 。更新maxLen = max(maxLen,len)
    • 否则,将len设置为1,即开始一个新的子序列。
  • 打印maxLen的值作为最终答案。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to find the longest non-decreasing
// subsequence with difference between
// adjacent elements exactly equal to 1
void longestSequence(int arr[], int N)
{
  // Base case
  if (N == 0) {
    cout << 0;
    return;
  }
 
  // Sort the array in ascending order
  sort(arr, arr+N);
 
  // Stores the maximum length
  int maxLen = 1;
 
  int len = 1;
 
  // Traverse the array
  for (int i = 1; i < N; i++) {
 
    // If difference between current
    // pair of adjacent elements is 1 or 0
    if (arr[i] == arr[i - 1]
        || arr[i] == arr[i - 1] + 1) {
      len++;
 
      // Extend the current sequence
      // Update len and max_len
      maxLen = max(maxLen, len);
    }
    else {
 
      // Otherwise, start a new subsequence
      len = 1;
    }
  }
 
  // Print the maximum length
  cout << maxLen;
}
 
 
// Driver Code
int main()
{
 
  // Given array
  int arr[] = { 8, 5, 4, 8, 4 };
 
  // Size of the array
  int N = sizeof(arr) / sizeof(arr[0]);
 
  // Function call to find the longest
  // subsequence
  longestSequence(arr, N);
 
  return 0;
}
 
// This code is contributed by code_hunt.


Java
// Java program for the above approach
 
import java.io.*;
import java.util.*;
class GFG {
 
    // Function to find the longest non-decreasing
    // subsequence with difference between
    // adjacent elements exactly equal to 1
    static void longestSequence(int arr[], int N)
    {
        // Base case
        if (N == 0) {
            System.out.println(0);
            return;
        }
 
        // Sort the array in ascending order
        Arrays.sort(arr);
 
        // Stores the maximum length
        int maxLen = 1;
 
        int len = 1;
 
        // Traverse the array
        for (int i = 1; i < N; i++) {
 
            // If difference between current
            // pair of adjacent elements is 1 or 0
            if (arr[i] == arr[i - 1]
                || arr[i] == arr[i - 1] + 1) {
                len++;
 
                // Extend the current sequence
                // Update len and max_len
                maxLen = Math.max(maxLen, len);
            }
            else {
 
                // Otherwise, start a new subsequence
                len = 1;
            }
        }
 
        // Print the maximum length
        System.out.println(maxLen);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array
        int arr[] = { 8, 5, 4, 8, 4 };
 
        // Size of the array
        int N = arr.length;
 
        // Function call to find the longest
        // subsequence
        longestSequence(arr, N);
    }
}


Python3
# Python program for the above approach
 
# Function to find the longest non-decreasing
# subsequence with difference between
# adjacent elements exactly equal to 1
def longestSequence(arr, N):
   
    # Base case
    if (N == 0):
        print(0);
        return;
 
    # Sort the array in ascending order
    arr.sort();
 
    # Stores the maximum length
    maxLen = 1;
    len = 1;
 
    # Traverse the array
    for i in range(1,N):
 
        # If difference between current
        # pair of adjacent elements is 1 or 0
        if (arr[i] == arr[i - 1] or arr[i] == arr[i - 1] + 1):
            len += 1;
 
            # Extend the current sequence
            # Update len and max_len
            maxLen = max(maxLen, len);
        else:
 
            # Otherwise, start a new subsequence
            len = 1;
 
    # Prthe maximum length
    print(maxLen);
 
# Driver Code
if __name__ == '__main__':
   
    # Given array
    arr = [8, 5, 4, 8, 4];
 
    # Size of the array
    N = len(arr);
 
    # Function call to find the longest
    # subsequence
    longestSequence(arr, N);
 
    # This code is contributed by 29AjayKumar


C#
// C# program for the above approach
using System;
public class GFG
{
 
  // Function to find the longest non-decreasing
  // subsequence with difference between
  // adjacent elements exactly equal to 1
  static void longestSequence(int []arr, int N)
  {
 
    // Base case
    if (N == 0)
    {
      Console.WriteLine(0);
      return;
    }
 
    // Sort the array in ascending order
    Array.Sort(arr);
 
    // Stores the maximum length
    int maxLen = 1;
    int len = 1;
 
    // Traverse the array
    for (int i = 1; i < N; i++) {
 
      // If difference between current
      // pair of adjacent elements is 1 or 0
      if (arr[i] == arr[i - 1]
          || arr[i] == arr[i - 1] + 1) {
        len++;
 
        // Extend the current sequence
        // Update len and max_len
        maxLen = Math.Max(maxLen, len);
      }
      else {
 
        // Otherwise, start a new subsequence
        len = 1;
      }
    }
 
    // Print the maximum length
    Console.WriteLine(maxLen);
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
 
    // Given array
    int []arr = { 8, 5, 4, 8, 4 };
 
    // Size of the array
    int N = arr.Length;
 
    // Function call to find the longest
    // subsequence
    longestSequence(arr, N);
  }
}
 
// This code is contributed by AnkThon


输出:
3

时间复杂度: O(N * logN)
辅助空间: O(1)