Queries to find longest subsequence having no similar adjacent elements with updates | javascript 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
function longestSubsequence ( N , Q , arr , Queries ) { var count = 1 ; for ( var i = 1 ; i < N ; i ++ ) { if ( arr [ i ] != arr [ i - 1 ] ) { count += 1 ; } } for ( var i = 0 ; i < Q ; i ++ ) { var x = Queries [ i ] [ 0 ] ; var y = Queries [ i ] [ 1 ] ; if ( x > 1 ) { if ( arr [ x - 1 ] != arr [ x - 2 ] ) { count -= 1 ; } if ( arr [ x - 2 ] != y ) { count += 1 ; } } if ( x < N ) { if ( arr [ x ] != arr [ x - 1 ] ) { count -= 1 ; } if ( y != arr [ x ] ) { count += 1 ; } } document . write ( count + " " ) ; arr [ x - 1 ] = y ; } } var arr = [ 1 , 1 , 2 , 5 , 2 ] ; var N = arr . length ; var Q = 2 ; var Queries = [ [ 1 , 3 ] , [ 4 , 2 ] ] ; longestSubsequence ( N , Q , arr , Queries ) ;