Maximum Unique Element in Every Subarray of Size K in C++
In this problem, we are given an array of integers and a integers K. our task is to create a program that will find the maximum unique element in every subarray of size K with no duplicates.
Let’s take an example to understand the problem,
Input −
array = {4, 1, 1, 3, 3} k = 3
Output −
4 3 1
Explanation −
Sub-array of size 3 Subarray {4, 1, 1}, max = 4 Subarray {1, 1, 3}, max = 3 Subarray {1, 3, 3}, max = 1
To solve this problem, one simple method is to run two loops and create subarrays and find distinct elements and print a maximum of them.
But an effective solution is to use a sliding window method using a hash table and self-balancing BST to find maximum elements.
So, we will traverse the array and for k length summary store the counts of elements in hash table and store the elements in a set (which will store only unique elements). And the print the max of the set and do the same for every iteration in the array.
Example
Program to illustrate the working of our solution,
#include <bits/stdc++.h> using namespace std; void maxUniqueSubArrayElement(int A[], int N, int K){ map<int, int> eleCount; for (int i = 0; i < K - 1; i++) eleCount[A[i]]++; set<int> uniqueMax; for (auto x : eleCount) if (x.second == 1) uniqueMax.insert(x.first); for (int i = K - 1; i < N; i++) { eleCount[A[i]]++; if (eleCount[A[i]] == 1) uniqueMax.insert(A[i]); else uniqueMax.erase(A[i]); if (uniqueMax.size() == 0) cout<<"-1\t" ; else cout<<*uniqueMax.rbegin()<<"\t"; int x = A[i - K + 1]; eleCount[x]--; if (eleCount[x] == 1) uniqueMax.insert(x); if (eleCount[x] == 0) uniqueMax.erase(x); } } int main(){ int a[] = { 4, 3, 2, 2, 3, 5}; int n = sizeof(a) / sizeof(a[0]); int k = 4; cout<<"The maximum unique element for a subarray of size "<<k<<" is\n"; maxUniqueSubArrayElement(a, n, k); return 0; }
Output
The maximum unique element for a subarray of size 4 is 4 -1 5