Given an array arr[] consisting of N integers and an integer K, the task is to find a subarray of size K with maximum sum and count of distinct elements same as that of the original array.
Examples:
Input: arr[] = {7, 7, 2, 4, 2, 7, 4, 6, 6, 6}, K = 6
Output: 31
Explanation: The given array consists of 4 distinct elements, i.e. {2, 4, 6, 7}. The subarray of size K consisting of all these elements and maximum sum is {2, 7, 4, 6, 6, 6} which starts from 5th index (1-based indexing) of the original array.
Therefore, the sum of the subarray = 2 + 7 + 4 + 6 + 6 + 6 = 31.Input: arr[] = {1, 2, 5, 5, 19, 2, 1}, K = 4
Output: 27
Naive Approach: The simple approach is to generate all possible subarrays of size K and check if it has the same distinct elements as the original array. If yes then find the sum of this subarray. After checking all the subarrays print the maximum sum of all such subarrays.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to count the number of // distinct elements present in the array int distinct( int arr[], int n) { Â Â Â Â map< int , int > mpp; Â
    // Insert all elements into the Set     for ( int i = 0; i < n; i++)     {         mpp[arr[i]] = 1;     } Â
    // Return the size of set     return mpp.size(); } Â
// Function that finds the maximum // sum of K-length subarray having // same unique elements as arr[] int maxSubSum( int arr[], int n, int k, int totalDistinct) {        // Not possible to find a     // subarray of size K     if (k > n)         return 0;     int maxm = 0, sum = 0;     for ( int i = 0; i < n - k + 1; i++)     {         sum = 0; Â
        // Initialize Set         set< int > st; Â
        // Calculate sum of the distinct elements         for ( int j = i; j < i + k; j++)         {             sum += arr[j];             st.insert(arr[j]);         } Â
        // If the set size is same as the         // count of distinct elements         if (( int ) st.size() == totalDistinct) Â
            // Update the maximum value             maxm = max(sum, maxm);     }     return maxm; } Â
// Driver code int main() { Â Â int arr[] = { 7, 7, 2, 4, 2, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 7, 4, 6, 6, 6 }; Â Â int K = 6; Â Â int N = sizeof (arr)/ sizeof (arr[0]); Â
  // Stores the count of distinct elements   int totalDistinct = distinct(arr, N);   cout << (maxSubSum(arr, N, K, totalDistinct)); Â
  return 0; } Â
// This code is contributed by mohit kumar 29. |
Java
// Java program for the above approach import java.util.*; Â
class GFG { Â
    // Function to count the number of     // distinct elements present in the array     static int distinct( int arr[], int n)     {         Set<Integer> set = new HashSet<>(); Â
        // Insert all elements into the Set         for ( int i = 0 ; i < n; i++) {             set.add(arr[i]);         } Â
        // Return the size of set         return set.size();     } Â
    // Function that finds the maximum     // sum of K-length subarray having     // same unique elements as arr[]     static int maxSubSum( int arr[], int n,                          int k,                          int totalDistinct)     {         // Not possible to find a         // subarray of size K         if (k > n)             return 0 ; Â
        int max = 0 , sum = 0 ; Â
        for ( int i = 0 ; i < n - k + 1 ; i++) {             sum = 0 ; Â
            // Initialize Set             Set<Integer> set = new HashSet<>(); Â
            // Calculate sum of the distinct elements             for ( int j = i; j < i + k; j++) {                 sum += arr[j];                 set.add(arr[j]);             } Â
            // If the set size is same as the             // count of distinct elements             if (set.size() == totalDistinct) Â
                // Update the maximum value                 max = Math.max(sum, max);         }         return max;     } Â
    // Driver Code     public static void main(String args[])     {         int arr[] = { 7 , 7 , 2 , 4 , 2 ,                       7 , 4 , 6 , 6 , 6 };         int K = 6 ;         int N = arr.length; Â
        // Stores the count of distinct elements         int totalDistinct = distinct(arr, N); Â
        System.out.println(             maxSubSum(arr, N, K, totalDistinct));     } } |
Python3
# Python3 program for the above approach Â
# Function to count the number of # distinct elements present in the array def distinct(arr, n): Â Â Â Â Â Â Â Â Â mpp = {} Â
    # Insert all elements into the Set     for i in range (n):         mpp[arr[i]] = 1 Â
    # Return the size of set     return len (mpp) Â
# Function that finds the maximum # sum of K-length subarray having # same unique elements as arr[] def maxSubSum(arr, n, k, totalDistinct):          # Not possible to find a     # subarray of size K     if (k > n):         return 0              maxm = 0     sum = 0          for i in range (n - k + 1 ):         sum = 0 Â
        # Initialize Set         st = set () Â
        # Calculate sum of the distinct elements         for j in range (i, i + k, 1 ):             sum + = arr[j]             st.add(arr[j]) Â
        # If the set size is same as the         # count of distinct elements         if ( len (st) = = totalDistinct):                          # Update the maximum value             maxm = max ( sum , maxm) Â
    return maxm Â
# Driver code if __name__ = = '__main__' : Â Â Â Â Â Â Â Â Â arr = [ 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 ] Â Â Â Â K = 6 Â Â Â Â N = len (arr) Â
    # Stores the count of distinct elements     totalDistinct = distinct(arr, N)     print (maxSubSum(arr, N, K, totalDistinct)) Â
# This code is contributed by ipg2016107 |
C#
// C# Program to implement // the above approach using System; using System.Collections.Generic; Â
class GFG { Â
Â
  // Function to count the number of   // distinct elements present in the array   static int distinct( int [] arr, int n)   {     HashSet< int > set = new HashSet< int >(); Â
    // Insert all elements into the Set     for ( int i = 0; i < n; i++) {       set .Add(arr[i]);     } Â
    // Return the size of set     return set .Count;   } Â
  // Function that finds the maximum   // sum of K-length subarray having   // same unique elements as arr[]   static int maxSubSum( int [] arr, int n,                        int k,                        int totalDistinct)   {     // Not possible to find a     // subarray of size K     if (k > n)       return 0; Â
    int max = 0, sum = 0; Â
    for ( int i = 0; i < n - k + 1; i++) {       sum = 0; Â
      // Initialize Set       HashSet< int > set = new HashSet< int >(); Â
      // Calculate sum of the distinct elements       for ( int j = i; j < i + k; j++) {         sum += arr[j];         set .Add(arr[j]);       } Â
      // If the set size is same as the       // count of distinct elements       if ( set .Count == totalDistinct) Â
        // Update the maximum value         max = Math.Max(sum, max);     }     return max;   } Â
  // Driver Code   public static void Main(String[] args)   {     int [] arr = { 7, 7, 2, 4, 2,                  7, 4, 6, 6, 6 };     int K = 6;     int N = arr.Length; Â
    // Stores the count of distinct elements     int totalDistinct = distinct(arr, N); Â
    Console.WriteLine(       maxSubSum(arr, N, K, totalDistinct));   } } Â
// This code is contributed by code_hunt. |
Javascript
<script> Â
// Javascript program for the above approach Â
// Function to count the number of // distinct elements present in the array function distinct(arr, n) { Â Â Â Â var mpp = new Map(); Â
    // Insert all elements into the Set     for ( var i = 0; i < n; i++)     {         mpp.set(arr[i], 1);     } Â
    // Return the size of set     return mpp.size; } Â
// Function that finds the maximum // sum of K-length subarray having // same unique elements as arr[] function maxSubSum(arr, n,k, totalDistinct) {        // Not possible to find a     // subarray of size K     if (k > n)         return 0;     var maxm = 0, sum = 0;     for ( var i = 0; i < n - k + 1; i++)     {         sum = 0; Â
        // Initialize Set         var st = new Set(); Â
        // Calculate sum of the distinct elements         for ( var j = i; j < i + k; j++)         {             sum += arr[j];             st.add(arr[j]);         } Â
        // If the set size is same as the         // count of distinct elements         if ( st.size == totalDistinct) Â
            // Update the maximum value             maxm = Math.max(sum, maxm);     }     return maxm; } Â
// Driver code var arr = [7, 7, 2, 4, 2, Â Â Â Â Â Â Â Â Â Â Â Â Â Â 7, 4, 6, 6, 6]; var K = 6; var N = arr.length; Â
// Stores the count of distinct elements var totalDistinct = distinct(arr, N); document.write(maxSubSum(arr, N, K, totalDistinct)); Â
// This code is contributed by itsok. </script> |
31
Â
Time Complexity: O(N2*log(N))
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to make use of Map. Follow the steps below to solve the problem:
- Traverse the array once and keep updating the frequency of array elements in the Map.
- Check if the size of the map is equal to the total number of distinct elements present in the original array or not. If found to be true, update the maximum sum.
- While traversing the original array, if the ith traversal crosses K elements in the array, update the Map by deleting an occurrence of (i – K)th element.
- After completing the above steps, print the maximum sum obtained.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include<bits/stdc++.h> using namespace std; Â
// Function to count the number of // distinct elements present in the array int distinct(vector< int >arr, int N) {     set< int > st;          // Insert array elements into set     for ( int i = 0; i < N; i++)     {         st.insert(arr[i]);     } Â
    // Return the st size     return st.size(); } Â
// Function to calculate maximum // sum of K-length subarray having // same unique elements as arr[] int maxSubarraySumUtil(vector< int >arr, int N,                        int K, int totalDistinct) {          // Not possible to find an     // subarray of length K from     // an N-sized array, if K > N     if (K > N)         return 0; Â
    int mx = 0;     int sum = 0; Â
    map< int , int > mp; Â
    // Traverse the array     for ( int i = 0; i < N; i++)     {                  // Update the mp         mp[arr[i]] += 1;         sum += arr[i]; Â
        // If i >= K, then decrement         // arr[i-K] element's one         // occurrence         if (i >= K)         {             mp[arr[i - K]] -= 1;             sum -= arr[i - K]; Â
            // If frequency of any             // element is 0 then             // remove the element             if (mp[arr[i - K]] == 0)                 mp.erase(arr[i - K]);         } Â
        // If mp size is same as the         // count of distinct elements         // of array arr[] then update         // maximum sum         if (mp.size() == totalDistinct)             mx = max(mx, sum);     }     return mx; } Â
// Function that finds the maximum // sum of K-length subarray having // same number of distinct elements // as the original array void maxSubarraySum(vector< int >arr,                            int K) {     // Size of array     int N = arr.size(); Â
    // Stores count of distinct elements     int totalDistinct = distinct(arr, N); Â
    // Print maximum subarray sum     cout<<maxSubarraySumUtil(arr, N, K, totalDistinct); } Â
// Driver Code int main() { Â Â Â Â vector< int >arr { 7, 7, 2, 4, 2, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 7, 4, 6, 6, 6 }; Â Â Â Â int K = 6; Â
    // Function Call     maxSubarraySum(arr, K); } Â
// This code is contributed by ipg2016107 |
Java
// Java program for the above approach Â
import java.util.*; class GFG { Â
    // Function to count the number of     // distinct elements present in the array     static int distinct( int arr[], int N)     {         Set<Integer> set = new HashSet<>(); Â
        // Insert array elements into Set         for ( int i = 0 ; i < N; i++) {             set.add(arr[i]);         } Â
        // Return the Set size         return set.size();     } Â
    // Function to calculate maximum     // sum of K-length subarray having     // same unique elements as arr[]     static int maxSubarraySumUtil(         int arr[], int N, int K,         int totalDistinct)     {         // Not possible to find an         // subarray of length K from         // an N-sized array, if K > N         if (K > N)             return 0 ; Â
        int max = 0 ;         int sum = 0 ; Â
        Map<Integer, Integer> map             = new HashMap<>(); Â
        // Traverse the array         for ( int i = 0 ; i < N; i++) { Â
            // Update the map             map.put(arr[i],                     map.getOrDefault(arr[i], 0 ) + 1 );             sum += arr[i]; Â
            // If i >= K, then decrement             // arr[i-K] element's one             // occurrence             if (i >= K) {                 map.put(arr[i - K],                         map.get(arr[i - K]) - 1 );                 sum -= arr[i - K]; Â
                // If frequency of any                 // element is 0 then                 // remove the element                 if (map.get(arr[i - K]) == 0 )                     map.remove(arr[i - K]);             } Â
            // If map size is same as the             // count of distinct elements             // of array arr[] then update             // maximum sum             if (map.size() == totalDistinct)                 max = Math.max(max, sum);         }         return max;     } Â
    // Function that finds the maximum     // sum of K-length subarray having     // same number of distinct elements     // as the original array     static void maxSubarraySum( int arr[],                                int K)     {         // Size of array         int N = arr.length; Â
        // Stores count of distinct elements         int totalDistinct = distinct(arr, N); Â
        // Print maximum subarray sum         System.out.println(             maxSubarraySumUtil(arr, N, K,                                totalDistinct));     } Â
    // Driver Code     public static void main(String args[])     {         int arr[] = { 7 , 7 , 2 , 4 , 2 ,                       7 , 4 , 6 , 6 , 6 };         int K = 6 ; Â
        // Function Call         maxSubarraySum(arr, K);     } } |
Python3
# Python 3 program for the above approach Â
# Function to count the number of # distinct elements present in the array def distinct(arr, N):     st = set ()          # Insert array elements into set     for i in range (N):         st.add(arr[i]) Â
    # Return the st size     return len (st) Â
# Function to calculate maximum # sum of K-length subarray having # same unique elements as arr[] def maxSubarraySumUtil(arr, N, K, totalDistinct):     # Not possible to find an     # subarray of length K from     # an N-sized array, if K > N     if (K > N):         return 0 Â
    mx = 0     sum = 0 Â
    mp = {} Â
    # Traverse the array     for i in range (N):         # Update the mp         if (arr[i] in mp):             mp[arr[i]] + = 1         else :             mp[arr[i]] = 1         sum + = arr[i] Â
        # If i >= K, then decrement         # arr[i-K] element's one         # occurrence         if (i > = K):             if (arr[i - K] in mp):                 mp[arr[i - K]] - = 1                 sum - = arr[i - K] Â
            # If frequency of any             # element is 0 then             # remove the element             if (arr[i - K] in mp and mp[arr[i - K]] = = 0 ):                 mp.remove(arr[i - K]) Â
        # If mp size is same as the         # count of distinct elements         # of array arr[] then update         # maximum sum         if ( len (mp) = = totalDistinct):             mx = max (mx, sum )     return mx Â
# Function that finds the maximum # sum of K-length subarray having # same number of distinct elements # as the original array def maxSubarraySum(arr, K):        # Size of array     N = len (arr) Â
    # Stores count of distinct elements     totalDistinct = distinct(arr, N) Â
    # Print maximum subarray sum     print (maxSubarraySumUtil(arr, N, K, totalDistinct)) Â
# Driver Code if __name__ = = '__main__' :     arr =  [ 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 ]     K = 6 Â
    # Function Call     maxSubarraySum(arr, K) Â
    # This code is contributed by SURENDRA_GANGWAR. |
C#
// C# program for the above approach using System; using System.Collections.Generic; Â
class GFG {   // Function to count the number of // distinct elements present in the array static int distinct(List< int >arr, int N) {     HashSet< int > st = new HashSet< int >();          // Insert array elements into set     for ( int i = 0; i < N; i++)     {         st.Add(arr[i]);     } Â
    // Return the st size     return st.Count; } Â
// Function to calculate maximum // sum of K-length subarray having // same unique elements as arr[] static int maxSubarraySumUtil(List< int >arr, int N,                        int K, int totalDistinct) {          // Not possible to find an     // subarray of length K from     // an N-sized array, if K > N     if (K > N)         return 0;     int mx = 0;     int sum = 0;     Dictionary< int , int > mp = new Dictionary< int , int >(); Â
    // Traverse the array     for ( int i = 0; i < N; i++)     {                  // Update the mp         if (mp.ContainsKey(arr[i]))             mp[arr[i]] += 1;         else             mp[arr[i]] = 1;         sum += arr[i]; Â
        // If i >= K, then decrement         // arr[i-K] element's one         // occurrence         if (i >= K)         {            if (mp.ContainsKey(arr[i - K]))               mp[arr[i - K]] -= 1;            else               mp[arr[i - K]] = 1;             sum -= arr[i - K]; Â
            // If frequency of any             // element is 0 then             // remove the element             if (mp[arr[i - K]] == 0)                 mp.Remove(arr[i - K]);         } Â
        // If mp size is same as the         // count of distinct elements         // of array arr[] then update         // maximum sum         if (mp.Count == totalDistinct)             mx = Math.Max(mx, sum);     }     return mx; } Â
// Function that finds the maximum // sum of K-length subarray having // same number of distinct elements // as the original array static void maxSubarraySum(List< int >arr,                            int K) {        // Size of array     int N = arr.Count; Â
    // Stores count of distinct elements     int totalDistinct = distinct(arr, N); Â
    // Print maximum subarray sum     Console.WriteLine(maxSubarraySumUtil(arr, N, K, totalDistinct)); } Â
// Driver Code public static void Main() { Â Â Â Â List< int >arr = new List< int >{ 7, 7, 2, 4, 2, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 7, 4, 6, 6, 6 }; Â Â Â Â int K = 6; Â
    // Function Call     maxSubarraySum(arr, K); } } Â
// This code is contributed by bgangwar59. |
Javascript
<script> Â
// JavaScript program for the above approach Â
// Function to count the number of // distinct elements present in the array function distinct(arr, N) {     var st = new Set();          // Insert array elements into set     for ( var i = 0; i < N; i++)     {         st.add(arr[i]);     } Â
    // Return the st size     return st.size; } Â
// Function to calculate maximum // sum of K-length subarray having // same unique elements as arr[] function maxSubarraySumUtil(arr, N, K, totalDistinct) {          // Not possible to find an     // subarray of length K from     // an N-sized array, if K > N     if (K > N)         return 0;      Â
    var mx = 0;     var sum = 0; Â
    var mp = new Map();          // Traverse the array     for ( var i=0; i<N; i++)     {                  // Update the mp         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, then decrement         // arr[i-K] element's one         // occurrence         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 frequency of any             // element is 0 then             // remove the element             if (mp.has(arr[i - K]) && mp.get(arr[i - K])== 0)                 mp. delete (arr[i - K]);         }                  // If mp size is same as the         // count of distinct elements         // of array arr[] then update         // maximum sum         if (mp.size == totalDistinct)             mx = Math.max(mx, sum);     }     return mx; } Â
// Function that finds the maximum // sum of K-length subarray having // same number of distinct elements // as the original array function maxSubarraySum(arr, K) {     // Size of array     var N = arr.length; Â
    // Stores count of distinct elements     var totalDistinct = distinct(arr, N); Â
    // Print maximum subarray sum     document.write( maxSubarraySumUtil(arr, N, K, totalDistinct)); } Â
// Driver Code Â
var arr = [7, 7, 2, 4, 2, Â Â Â Â Â Â Â Â Â Â Â 7, 4, 6, 6, 6 ]; var K = 6; Â
// Function Call maxSubarraySum(arr, K); Â
Â
</script> |
31
Â
Time Complexity: O(N*log (N))
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!