Maximum sum of K | Java program for 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
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 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 ; Set < Integer > set = new HashSet < > ( ) ; for ( int j = i ; j < i + k ; j ++ ) { sum += arr [ j ] ; set . add ( arr [ j ] ) ; } if ( set . size ( ) == 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 ) ; System . out . println ( maxSubSum ( arr , N , K , totalDistinct ) ) ; } }