Find sum of all unique elements in the array for K queries | Java 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 final array ; Variable to store the sum ; Hash to maintain perviously occured elements ; Loop to find the maximum sum ; Driver code
import java . util . * ; 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 < Integer > s = new HashSet < Integer > ( ) ; 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 . length ; System . out . print ( uniqueSum ( A , R , N , M ) ) ; } }