Find sum of all unique elements in the array for K queries | C # implementation to find the sum of all unique elements of the array after Q 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 readonly array ; Variable to store the sum ; Hash to maintain perviously occured elements ; Loop to find the maximum sum ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int uniqueSum ( int [ ] A , int [ , ] R , int N , int M ) { for ( int i = 0 ; i < M ; ++ i ) { int l = R [ i , 0 ] , r = R [ i , 1 ] + 1 ; l -- ; r -- ; A [ l ] ++ ; if ( r < N ) A [ r ] -- ; } for ( int i = 1 ; i < N ; ++ i ) { A [ i ] += A [ i - 1 ] ; } int ans = 0 ; HashSet < int > s = new HashSet < int > ( ) ; for ( int i = 0 ; i < N ; ++ i ) { if ( ! s . Contains ( A [ i ] ) ) ans += A [ i ] ; s . Add ( A [ i ] ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] A = { 0 , 0 , 0 , 0 , 0 , 0 } ; int [ , ] R = { { 1 , 3 } , { 4 , 6 } , { 3 , 4 } , { 3 , 3 } } ; int N = A . Length ; int M = R . GetLength ( 0 ) ; Console . Write ( uniqueSum ( A , R , N , M ) ) ; } }