Maximum sum of K | C # Program to implement the above approach ; Function to count the number of distinct elements present in the array ; Insert all elements into the Set ; Return the size of set ; Function that finds the maximum sum of K - length subarray having same unique elements as arr [ ] ; Not possible to find a subarray of size K ; Initialize Set ; Calculate sum of the distinct elements ; If the set size is same as the count of distinct elements ; Update the maximum value ; Driver Code ; Stores the count of distinct elements
using System ; using System . Collections . Generic ; class GFG { static int distinct ( int [ ] arr , int n ) { HashSet < int > set = new HashSet < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { set . Add ( arr [ i ] ) ; } return set . Count ; } static int maxSubSum ( int [ ] arr , int n , int k , int totalDistinct ) { if ( k > n ) return 0 ; int max = 0 , sum = 0 ; for ( int i = 0 ; i < n - k + 1 ; i ++ ) { sum = 0 ; HashSet < int > set = new HashSet < int > ( ) ; for ( int j = i ; j < i + k ; j ++ ) { sum += arr [ j ] ; set . Add ( arr [ j ] ) ; } if ( set . Count == totalDistinct ) max = Math . Max ( sum , max ) ; } return max ; } public static void Main ( String [ ] args ) { int [ ] arr = { 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 } ; int K = 6 ; int N = arr . Length ; int totalDistinct = distinct ( arr , N ) ; Console . WriteLine ( maxSubSum ( arr , N , K , totalDistinct ) ) ; } }