Maximum sum of K | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinct ( vector < int > arr , int N ) { set < int > st ; for ( int i = 0 ; i < N ; i ++ ) { st . insert ( arr [ i ] ) ; } return st . size ( ) ; } int maxSubarraySumUtil ( vector < int > arr , int N , int K , int totalDistinct ) { if ( K > N ) return 0 ; int mx = 0 ; int sum = 0 ; map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] += 1 ; sum += arr [ i ] ; if ( i >= K ) { mp [ arr [ i - K ] ] -= 1 ; sum -= arr [ i - K ] ; if ( mp [ arr [ i - K ] ] == 0 ) mp . erase ( arr [ i - K ] ) ; } if ( mp . size ( ) == totalDistinct ) mx = max ( mx , sum ) ; } return mx ; } void maxSubarraySum ( vector < int > arr , int K ) { int N = arr . size ( ) ; int totalDistinct = distinct ( arr , N ) ; cout << maxSubarraySumUtil ( arr , N , K , totalDistinct ) ; } int main ( ) { vector < int > arr { 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 } ; int K = 6 ; maxSubarraySum ( arr , K ) ; }