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