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++
#include <bits/stdc++.h>
using namespace std;
void longestSubsequence( int arr[], int N)
{
int count = 1;
for ( int i = 1; i < N; i++) {
if (arr[i] != arr[i - 1]) {
count++;
}
}
cout << count << endl;
}
int main()
{
int arr[] = { 7, 8, 1, 2, 2, 5, 5, 1 };
int N = sizeof (arr) / sizeof (arr[0]);
longestSubsequence(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void longestSubsequence( int arr[],
int N)
{
int count = 1 ;
for ( int i = 1 ; i < N; i++)
{
if (arr[i] != arr[i - 1 ])
{
count++;
}
}
System.out.println(count);
}
public static void main(String args[])
{
int arr[] = { 7 , 8 , 1 , 2 ,
2 , 5 , 5 , 1 };
int N = arr.length;
longestSubsequence(arr, N);
}
}
|
Python3
def longestSubsequence(arr, N):
count = 1
for i in range ( 1 , N, 1 ):
if (arr[i] ! = arr[i - 1 ]):
count + = 1
print (count)
if __name__ = = '__main__' :
arr = [ 7 , 8 , 1 , 2 , 2 , 5 , 5 , 1 ]
N = len (arr)
longestSubsequence(arr, N)
|
C#
using System;
class GFG{
static void longestSubsequence( int [] arr,
int N)
{
int count = 1;
for ( int i = 1; i < N; i++)
{
if (arr[i] != arr[i - 1])
{
count++;
}
}
Console.WriteLine(count);
}
public static void Main()
{
int [] arr = { 7, 8, 1, 2,
2, 5, 5, 1 };
int N = arr.Length;
longestSubsequence(arr, N);
}
}
|
Javascript
<script>
function longestSubsequence(arr, N)
{
let count = 1;
for (let i = 1; i < N; i++)
{
if (arr[i] != arr[i - 1])
{
count++;
}
}
document.write(count);
}
let arr = [7, 8, 1, 2,
2, 5, 5, 1];
let N = arr.length;
longestSubsequence(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)