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
def distinct ( arr , N ) : NEW_LINE INDENT st = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT st . add ( arr [ i ] ) NEW_LINE DEDENT return len ( st ) NEW_LINE DEDENT def maxSubarraySumUtil ( arr , N , K , totalDistinct ) : NEW_LINE INDENT if ( K > N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT mx = 0 NEW_LINE sum = 0 NEW_LINE mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] in mp ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT sum += arr [ i ] NEW_LINE if ( i >= K ) : NEW_LINE INDENT if ( arr [ i - K ] in mp ) : NEW_LINE INDENT mp [ arr [ i - K ] ] -= 1 NEW_LINE sum -= arr [ i - K ] NEW_LINE DEDENT if ( arr [ i - K ] in mp and mp [ arr [ i - K ] ] == 0 ) : NEW_LINE INDENT mp . remove ( arr [ i - K ] ) NEW_LINE DEDENT DEDENT if ( len ( mp ) == totalDistinct ) : NEW_LINE INDENT mx = max ( mx , sum ) NEW_LINE DEDENT DEDENT return mx NEW_LINE DEDENT def maxSubarraySum ( arr , K ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE totalDistinct = distinct ( arr , N ) NEW_LINE print ( maxSubarraySumUtil ( arr , N , K , totalDistinct ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 ] NEW_LINE K = 6 NEW_LINE maxSubarraySum ( arr , K ) NEW_LINE DEDENT