Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Length of longest non-decreasing subsequence such that difference between adjacent elements is at most one
Next article icon

Length of longest subsequence consisting of distinct adjacent elements

Last Updated : 21 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[], the task is to find the length of the longest subsequence of the array arr[] such that all adjacent elements in the subsequence are different.

Examples:

Input: arr[] = {4, 2, 3, 4, 3}
Output: 5
Explanation:
The longest subsequence where no two adjacent elements are equal is {4, 2, 3, 4, 3}. Length of the subsequence is 5.

Input: arr[] = {7, 8, 1, 2, 2, 5, 5, 1}
Output: 6
Explanation: Longest subsequence where no two adjacent elements are equal is {7, 8, 1, 2, 5, 1}. Length of the subsequence is 5.

Naive Approach: The simplest approach is to generate all possible subsequence of the given array and print the maximum length of that subsequence having all adjacent elements different. 

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

Efficient Approach: Follow the steps below to solve the problem:

  • Initialize count to 1 to store the length of the longest subsequence.
  • Traverse the array over the indices [1, N – 1] and for each element, check if the current element is equal to the previous element or not. If found to be not equal, then increment count by 1.
  • After completing the above steps, print the value of count as the maximum possible length of subsequence.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that finds the length of
// longest subsequence having different
// adjacent elements
void longestSubsequence(int arr[], int N)
{
    // Stores the length of the
    // longest subsequence
    int count = 1;
 
    // Traverse the array
    for (int i = 1; i < N; i++) {
 
        // If previous and current
        // element are not same
        if (arr[i] != arr[i - 1]) {
 
            // Increment the count
            count++;
        }
    }
 
    // Print the maximum length
    cout << count << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 7, 8, 1, 2, 2, 5, 5, 1 };
 
    // Size of Array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    longestSubsequence(arr, N);
 
    return 0;
}
 
 

Java




// Java program for the
// above approach
import java.util.*;
 
class GFG{
    
// Function that finds the length of
// longest subsequence having different
// adjacent elements
static void longestSubsequence(int arr[],
                               int N)
{
  // Stores the length of the
  // longest subsequence
  int count = 1;
 
  // Traverse the array
  for (int i = 1; i < N; i++)
  {
    // If previous and current
    // element are not same
    if (arr[i] != arr[i - 1])
    {
      // Increment the count
      count++;
    }
  }
 
  // Print the maximum length
  System.out.println(count);
}
 
// Driver Code
public static void main(String args[])
{
  int arr[] = {7, 8, 1, 2,
               2, 5, 5, 1};
 
  // Size of Array
  int N = arr.length;
 
  // Function Call
  longestSubsequence(arr, N);
}
}
 
// This code is contributed by bgangwar59
 
 

Python3




# Python3 program for the above approach
 
# Function that finds the length of
# longest subsequence having different
# adjacent elements
def longestSubsequence(arr, N):
     
    # Stores the length of the
    # longest subsequence
    count = 1
 
    # Traverse the array
    for i in range(1, N, 1):
         
        # If previous and current
        # element are not same
        if (arr[i] != arr[i - 1]):
             
            # Increment the count
            count += 1
 
    # Print the maximum length
    print(count)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 7, 8, 1, 2, 2, 5, 5, 1 ]
     
    # Size of Array
    N = len(arr)
     
    # Function Call
    longestSubsequence(arr, N)
 
# This code is contributed by ipg2016107
 
 

C#




// C# program for the
// above approach
using System;
  
class GFG{
     
// Function that finds the length of
// longest subsequence having different
// adjacent elements
static void longestSubsequence(int[] arr,
                               int N)
{
   
  // Stores the length of the
  // longest subsequence
  int count = 1;
  
  // Traverse the array
  for(int i = 1; i < N; i++)
  {
     
    // If previous and current
    // element are not same
    if (arr[i] != arr[i - 1])
    {
       
      // Increment the count
      count++;
    }
  }
  
  // Print the maximum length
  Console.WriteLine(count);
}
  
// Driver Code
public static void Main()
{
  int[] arr = { 7, 8, 1, 2,
                2, 5, 5, 1 };
   
  // Size of Array
  int N = arr.Length;
   
  // Function Call
  longestSubsequence(arr, N);
}
}
 
// This code is contributed by susmitakundugoaldanga
 
 

Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Function that finds the length of
// longest subsequence having different
// adjacent elements
function longestSubsequence(arr, N)
{
  // Stores the length of the
  // longest subsequence
  let count = 1;
  
  // Traverse the array
  for (let i = 1; i < N; i++)
  {
    // If previous and current
    // element are not same
    if (arr[i] != arr[i - 1])
    {
      // Increment the count
      count++;
    }
  }
  
  // Print the maximum length
  document.write(count);
}
 
// Driver Code
 
    let arr = [7, 8, 1, 2,
               2, 5, 5, 1];
  
  // Size of Array
  let N = arr.length;
  
  // Function Call
  longestSubsequence(arr, N);
           
</script>
 
 
Output: 
6

 

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



Next Article
Length of longest non-decreasing subsequence such that difference between adjacent elements is at most one
author
supratik_mitra
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • School Programming
  • frequency-counting
  • subsequence
Practice Tags :
  • Arrays
  • Greedy

Similar Reads

  • Length of the longest subsequence consisting of distinct elements
    Given an array arr[] of size N, the task is to find the length of the longest subsequence consisting of distinct elements only. Examples: Input: arr[] = {1, 1, 2, 2, 2, 3, 3} Output: 3 Explanation: The longest subsequence with distinct elements is {1, 2, 3} Input: arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 }
    4 min read
  • Length of largest subsequence consisting of a pair of alternating digits
    Given a numeric string s consisting of digits 0 to 9, the task is to find the length of the largest subsequence consisting of a pair of alternating digits. An alternating digits subsequence consisting of two different digits a and b can be represented as “abababababababababab....". Examples: Input:
    7 min read
  • Longest subsequence such that adjacent elements have at least one common digit
    Given an array arr[], the task is to find the length of the longest sub-sequence such that adjacent elements of the subsequence have at least one digit in common. Examples: Input: arr[] = [1, 12, 44, 29, 33, 96, 89] Output: 5 Explanation: The longest sub-sequence is [1 12 29 96 89] Input: arr[] = [1
    15+ min read
  • Length of longest non-decreasing subsequence such that difference between adjacent elements is at most one
    Given an array arr[] consisting of N integers, the task is to find the length of the longest non-decreasing subsequence such that the difference between adjacent elements is at most 1. Examples: Input: arr[] = {8, 5, 4, 8, 4}Output: 3Explanation: {4, 4, 5}, {8, 8} are the two such non-decreasing sub
    6 min read
  • Count of subsequences having maximum distinct elements
    Given an arr of size n. The problem is to count all the subsequences having maximum number of distinct elements. Examples: Input : arr[] = {4, 7, 6, 7} Output : 2 The indexes for the subsequences are: {0, 1, 2} - Subsequence is {4, 7, 6} and {0, 2, 3} - Subsequence is {4, 6, 7} Input : arr[] = {9, 6
    5 min read
  • Length of Longest subarray such that difference between adjacent elements is K
    Given an array arr[] of size N, and integer K. The task is to find the length of the longest subarray with the difference between adjacent elements as K. Examples: Input: arr[] = { 5, 5, 5, 10, 8, 6, 12, 13 }, K =1Output: 2Explanation: Only one subarray which have difference between adjacents as 1 i
    5 min read
  • Longest subsequence having maximum GCD between any pair of distinct elements
    Given an array arr[] consisting of N positive integers, the task is to find the maximum length of subsequence from the given array such that the GCD of any two distinct integers of the subsequence is maximum. Examples: Input: arr[] = {5, 14, 15, 20, 1}Output: 3Explanation: Subsequence with maximum G
    15+ min read
  • Longest Common Subsequence of two arrays out of which one array consists of distinct elements only
    Given two arrays firstArr[], consisting of distinct elements only, and secondArr[], the task is to find the length of LCS between these 2 arrays. Examples: Input: firstArr[] = {3, 5, 1, 8}, secondArr[] = {3, 3, 5, 3, 8}Output: 3.Explanation: LCS between these two arrays is {3, 5, 8}. Input : firstAr
    7 min read
  • Length of longest increasing index dividing subsequence
    Given an array arr[] of size N, the task is to find the longest increasing sub-sequence such that index of any element is divisible by index of previous element (LIIDS). The following are the necessary conditions for the LIIDS:If i, j are two indices in the given array. Then: i < jj % i = 0arr[i]
    7 min read
  • Maximize count of distinct elements in a subsequence of size K in given array
    Given an array arr[] of N integers and an integer K, the task is to find the maximum count of distinct elements over all the subsequences of K integers. Example: Input: arr[]={1, 1, 2, 2}, K=3Output: 2Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences