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
def uniqueSum ( A , R , N , M ) : NEW_LINE INDENT for i in range ( 0 , M ) : NEW_LINE INDENT l = R [ i ] [ 0 ] NEW_LINE r = R [ i ] [ 1 ] + 1 NEW_LINE l -= 1 NEW_LINE r -= 1 NEW_LINE A [ l ] += 1 NEW_LINE if ( r < N ) : NEW_LINE INDENT A [ r ] -= 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT A [ i ] += A [ i - 1 ] NEW_LINE DEDENT ans = 0 NEW_LINE s = { chr } NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( A [ i ] not in s ) : NEW_LINE INDENT ans += A [ i ] NEW_LINE DEDENT s . add ( A [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT A = [ 0 , 0 , 0 , 0 , 0 , 0 ] NEW_LINE R = [ [ 1 , 3 ] , [ 4 , 6 ] , [ 3 , 4 ] , [ 3 , 3 ] ] NEW_LINE N = len ( A ) NEW_LINE M = len ( R ) NEW_LINE print ( uniqueSum ( A , R , N , M ) ) NEW_LINE