Maximum sum of K | Java program for the above approach ; Function to count the number of distinct elements present in the array ; Insert array elements into Set ; Return the Set size ; Function to calculate maximum sum of K - length subarray having same unique elements as arr [ ] ; Not possible to find an subarray of length K from an N - sized array , if K > N ; Traverse the array ; Update the map ; If i >= K , then decrement arr [ i - K ] element 's one  occurence ; If frequency of any element is 0 then remove the element ; If map size is same as the count of distinct elements of array arr [ ] then update maximum sum ; Function that finds the maximum sum of K - length subarray having same number of distinct elements as the original array ; Size of array ; Stores count of distinct elements ; Print maximum subarray sum ; Driver Code ; Function Call
import java . util . * ; class GFG { static int distinct ( int arr [ ] , int N ) { Set < Integer > set = new HashSet < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { set . add ( arr [ i ] ) ; } return set . size ( ) ; } static int maxSubarraySumUtil ( int arr [ ] , int N , int K , int totalDistinct ) { if ( K > N ) return 0 ; int max = 0 ; int sum = 0 ; Map < Integer , Integer > map = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { map . put ( arr [ i ] , map . getOrDefault ( arr [ i ] , 0 ) + 1 ) ; sum += arr [ i ] ; if ( i >= K ) { map . put ( arr [ i - K ] , map . get ( arr [ i - K ] ) - 1 ) ; sum -= arr [ i - K ] ; if ( map . get ( arr [ i - K ] ) == 0 ) map . remove ( arr [ i - K ] ) ; } if ( map . size ( ) == totalDistinct ) max = Math . max ( max , sum ) ; } return max ; } static void maxSubarraySum ( int arr [ ] , int K ) { int N = arr . length ; int totalDistinct = distinct ( arr , N ) ; System . out . println ( maxSubarraySumUtil ( arr , N , K , totalDistinct ) ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 } ; int K = 6 ; maxSubarraySum ( arr , K ) ; } }