Maximum sum of K-length subarray consisting of same number of distinct elements as the given array
Last Updated :
29 Dec, 2022
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>
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>
Time Complexity: O(N*log (N))
Auxiliary Space: O(N)
Similar Reads
Maximum length of subarray consisting of same type of element on both halves of sub-array
Given an array arr[] of N integers, the task is to find the maximum length of sub-array consisting of the same type of element on both halves of the sub-array. Also, the elements on both halves differ from each other. Examples: Input: arr[] = {2, 3, 4, 4, 5, 5, 6, 7, 8, 10}Output: 4Explanation:{2, 3
8 min read
Maximum sum of subarrays having distinct elements of length K
Given an array, arr[] and a value k, represent the length of the subarray to be considered. Find the maximum sum that can be obtained from the subarray of length k such that each element of the subarray is unique. If there is no subarray that meets the required condition then return 0. Examples: Inp
13 min read
Maximum sum of K-length subarray with maximum count of distinct prime factors
Given an array arr[] consisting of N positive integers and an integer K, the task is to find the maximum sum of array elements in a subarray having maximum sum of distinct prime factors in each K-length subarray. Note: If there are multiple answers then print the sum of the original subarray having
11 min read
Maximize count of distinct elements in a subsequence of size K in given array
Given an array arr[] of N integers and an integer K, the task is to find the maximum count of distinct elements over all the subsequences of K integers. Example: Input: arr[]={1, 1, 2, 2}, K=3Output: 2Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are
4 min read
Maximize length of longest subarray consisting of same elements by at most K decrements
Given an array arr[] of size N and an integer K, the task is to find the length of the longest subarray consisting of same elements that can be obtained by decrementing the array elements by 1 at most K times. Example: Input: arr[] = { 1, 2, 3 }, K = 1Output: 2Explanation:Decrementing arr[0] by 1 mo
15+ min read
Minimum number of distinct elements present in a K-length subsequence in an array
Given an array A[] consisting of N integers and an integer K, the task is to count the minimum number of distinct elements present in a subsequence of length K of the given array, A. Examples: Input: A = {3, 1, 3, 2, 3, 4, 5, 4}, K = 4Output: 2Explanation: The subsequence of length 4 containing mini
7 min read
Length of smallest subarray consisting of all occurrences of all maximum occurring elements
Given an array arr[] of size N, The task is to find the length of the smallest subarray consisting of all the occurrences of maximum occurring elementsExamples: Input: arr[] = {1, 2, 1, 3, 2}Output: 5Explanation: Elements with maximum frequency (=2) are 1 & 2. Therefore, the length of smallest s
6 min read
Maximum count of sub-strings of length K consisting of same characters
Given a string str and an integer k. The task is to count the occurrences of sub-strings of length k that consist of the same characters. There can be multiple such sub-strings possible of length k, choose the count of the one which appears the maximum number of times as the sub-string (non-overlapp
6 min read
Maximum length of same indexed subarrays from two given arrays satisfying the given condition
Given two arrays arr[] and brr[] and an integer C, the task is to find the maximum possible length, say K, of the same indexed subarrays such that the sum of the maximum element in the K-length subarray in brr[] with the product between K and sum of the K-length subarray in arr[] does not exceed C.
15+ min read
Length of the longest subsequence consisting of distinct elements
Given an array arr[] of size N, the task is to find the length of the longest subsequence consisting of distinct elements only. Examples: Input: arr[] = {1, 1, 2, 2, 2, 3, 3} Output: 3 Explanation: The longest subsequence with distinct elements is {1, 2, 3} Input: arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 }
4 min read