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
def distinct ( arr , n ) : NEW_LINE INDENT mpp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mpp [ arr [ i ] ] = 1 NEW_LINE DEDENT return len ( mpp ) NEW_LINE DEDENT def maxSubSum ( arr , n , k , totalDistinct ) : NEW_LINE INDENT if ( k > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT maxm = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( n - k + 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE st = set ( ) NEW_LINE for j in range ( i , i + k , 1 ) : NEW_LINE INDENT sum += arr [ j ] NEW_LINE st . add ( arr [ j ] ) NEW_LINE DEDENT if ( len ( st ) == totalDistinct ) : NEW_LINE INDENT maxm = max ( sum , maxm ) NEW_LINE DEDENT DEDENT return maxm 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 N = len ( arr ) NEW_LINE totalDistinct = distinct ( arr , N ) NEW_LINE print ( maxSubSum ( arr , N , K , totalDistinct ) ) NEW_LINE DEDENT