Find sum of all unique elements in the array for K queries | Function to find the sum of unique elements after Q Query ; Updating the array after processing each query ; Making it to 0 - indexing ; Iterating over the array to get the final array ; Variable to store the sum ; Hash to maintain perviously occured elements ; Loop to find the maximum sum ; Driver code
function uniqueSum ( A , R , N , M ) { for ( let i = 0 ; i < M ; ++ i ) { let l = R [ i ] [ 0 ] , r = R [ i ] [ 1 ] + 1 ; l -- ; r -- ; A [ l ] ++ ; if ( r < N ) A [ r ] -- ; } for ( let i = 1 ; i < N ; ++ i ) { A [ i ] += A [ i - 1 ] ; } let ans = 0 ; let s = new Set ( ) ; for ( let i = 0 ; i < N ; ++ i ) { if ( ! s . has ( A [ i ] ) ) ans += A [ i ] ; s . add ( A [ i ] ) ; } return ans ; } let A = [ 0 , 0 , 0 , 0 , 0 , 0 ] ; let R = [ [ 1 , 3 ] , [ 4 , 6 ] , [ 3 , 4 ] , [ 3 , 3 ] ] ; let N = A . length ; let M = R . length ; document . write ( uniqueSum ( A , R , N , M ) ) ;