Maximum sum of K | 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
function distinct ( arr , n ) { var mpp = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { mpp . set ( arr [ i ] , 1 ) ; } return mpp . size ; } function maxSubSum ( arr , n , k , totalDistinct ) { if ( k > n ) return 0 ; var maxm = 0 , sum = 0 ; for ( var i = 0 ; i < n - k + 1 ; i ++ ) { sum = 0 ; var st = new Set ( ) ; for ( var j = i ; j < i + k ; j ++ ) { sum += arr [ j ] ; st . add ( arr [ j ] ) ; } if ( st . size == totalDistinct ) maxm = Math . max ( sum , maxm ) ; } return maxm ; } var arr = [ 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 ] ; var K = 6 ; var N = arr . length ; var totalDistinct = distinct ( arr , N ) ; document . write ( maxSubSum ( arr , N , K , totalDistinct ) ) ;