Maximum sum of K | Function to count the number of distinct elements present in the array ; Insert array elements into set ; Return the st 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 mp ; If i >= K , then decrement arr [ i - K ] element 's one  occurence ; If frequency of any element is 0 then remove the element ; If mp 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
function distinct ( arr , N ) { var st = new Set ( ) ; for ( var i = 0 ; i < N ; i ++ ) { st . add ( arr [ i ] ) ; } return st . size ; } function maxSubarraySumUtil ( arr , N , K , totalDistinct ) { if ( K > N ) return 0 ; var mx = 0 ; var sum = 0 ; var mp = new Map ( ) ; for ( var i = 0 ; i < N ; i ++ ) { if ( mp . has ( arr [ i ] ) ) mp . set ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) else mp . set ( arr [ i ] , 1 ) sum += arr [ i ] ; if ( i >= K ) { if ( mp . has ( arr [ i - K ] ) ) mp . set ( arr [ i - K ] , mp . get ( arr [ i - K ] ) - 1 ) sum -= arr [ i - K ] ; if ( mp . has ( arr [ i - K ] ) && mp . get ( arr [ i - K ] ) == 0 ) mp . delete ( arr [ i - K ] ) ; } if ( mp . size == totalDistinct ) mx = Math . max ( mx , sum ) ; } return mx ; } function maxSubarraySum ( arr , K ) { var N = arr . length ; var totalDistinct = distinct ( arr , N ) ; document . write ( maxSubarraySumUtil ( arr , N , K , totalDistinct ) ) ; } var arr = [ 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 ] ; var K = 6 ; maxSubarraySum ( arr , K ) ;