text: Queries to find longest subsequence having no similar adjacent elements with updates | Python3 program for the above approach ; Traverse the array arr [ ] ; If previous element is not same as current element ; Traverse the queries ; Replace element at index x with y ; Recalculate for index x ; Subtract contribution of element at index x ; Add contribution of y ; Recalculate for index x + 1 ; Subtract contribution of element at index x + 1 ; Adds contribution of y ; Replace the element ; Driver Code ; Function Call
code: def longestSubsequence ( N , Q , arr , Queries ) : NEW_LINE INDENT count = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT for i in range ( Q ) : NEW_LINE INDENT x = Queries [ i ] [ 0 ] NEW_LINE y = Queries [ i ] [ 1 ] NEW_LINE if ( x > 1 ) : NEW_LINE INDENT if ( arr [ x - 1 ] != arr [ x - 2 ] ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( arr [ x - 2 ] != y ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( x < N ) : NEW_LINE INDENT if ( arr [ x ] != arr [ x - 1 ] ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( y != arr [ x ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count , end = ' ▁ ' ) NEW_LINE arr [ x - 1 ] = y NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 5 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE Q = 2 NEW_LINE Queries = [ [ 1 , 3 ] , [ 4 , 2 ] ] NEW_LINE longestSubsequence ( N , Q , arr , Queries ) NEW_LINE DEDENT