Saturday, February 20, 2021

Published February 20, 2021 by Anonymous with 0 comment

Length of longest non-decreasing subsequence such that difference between adjacent elements is at most one

  

import java.io.*;

import java.util.*;

class GFG {

  

    

    

    

    static void longestSequence(int arr[], int N)

    {

        

        if (N == 0) {

            System.out.println(0);

            return;

        }

  

        

        Arrays.sort(arr);

  

        

        int maxLen = 1;

  

        int len = 1;

  

        

        for (int i = 1; i < N; i++) {

  

            

            

            if (arr[i] == arr[i - 1]

                || arr[i] == arr[i - 1] + 1) {

                len++;

  

                

                

                maxLen = Math.max(maxLen, len);

            }

            else {

  

                

                len = 1;

            }

        }

  

        

        System.out.println(maxLen);

    }

  

    

    public static void main(String[] args)

    {

        

        int arr[] = { 8, 5, 4, 8, 4 };

  

        

        int N = arr.length;

  

        

        

        longestSequence(arr, N);

    }

}

Let's block ads! (Why?)

      edit

0 comments:

Post a Comment