Queries to find longest subsequence having no similar adjacent elements with updates | Java program for the above approach ; Function to find the length of the longest subsequence such that no two adjacent elements are equal ; Replace element at index x with y ; Since x is 1 - indexed , decrement x by 1 ; Keep track of number of elements in subsequence ; If previous element is not same as current element ; Print the desired count ; Driver Code ; Function Call
import java . util . * ; class GFG { static void longestSubsequence ( int N , int Q , int arr [ ] , int Queries [ ] [ ] ) { for ( int i = 0 ; i < Q ; i ++ ) { int x = Queries [ i ] [ 0 ] ; int y = Queries [ i ] [ 1 ] ; arr [ x - 1 ] = y ; int count = 1 ; for ( int j = 1 ; j < N ; j ++ ) { if ( arr [ j ] != arr [ j - 1 ] ) { count += 1 ; } } System . out . print ( count + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 5 , 2 } ; int N = arr . length ; int Q = 2 ; int Queries [ ] [ ] = { { 1 , 3 } , { 4 , 2 } } ; longestSubsequence ( N , Q , arr , Queries ) ; } }