Maximum Unique Element in every subarray of size K in c++

C++Server Side ProgrammingProgramming

Problem statement

Given an array and an integer K. We need to find the maximum of every segment of length K which has no duplicates in that segment

If input array is {5, 7, 5, 2, 1} and K = 3 then we get following result −

1. {5, 7, 5} Maximum unique element is 7
2. {7, 5, 2} Maximum unique element is 7
3. {5, 2, 1} Maximum unique element is 5

Algorithm

We can use a sliding window technique. We maintain the following two structures in every window −

1. A hash table to store counts of all elements in current window
2. A self-balancing BST (implemented using set in C++ STL and TreeSet in Java).
   The idea is to quickly find maximum element and update maximum element
3. Process first K-1 elements and store their counts in hash table
4. Store unique elements in set
5. One by one process last element of every window. If current element is unique,
   then add it to set. Also increase its count
6. After processing last element, print the maximum from set

Example

#include <bits/stdc++.h>
using namespace std;
void find_max(int arr[], int n, int k){
   map<int, int> count;
   for (int i = 0; i < k - 1; ++i) {
      count[arr[i]]++;
   }
   set<int> mySet;
   for (auto x : count) {
      if (x.second == 1) {
         mySet.insert(x.first);
      }
   }
   for (int i = k - 1; i < n; ++i) {
      count[arr[i]]++;
      if (count[arr[i]] == 1) {
         mySet.insert(arr[i]);
      } else {
         mySet.erase(arr[i]);
      }
      if (mySet.size() == 0) {
         cout << "Nothing\n";
      } else {
         cout << "Maximum unique from set: ";
         cout << *mySet.rbegin() << endl;
      }
      int x = arr[i - k + 1];
      count[x]--;
      if (count[x] == 1) {
         mySet.insert(x);
      }
      if (count[x] == 0) {
         mySet.erase(x);
      }
   }
}
int main(){
   int a[] = {5, 7, 5, 2, 1};
   int n = sizeof(a) / sizeof(a[0]);
   int k = 3;
   find_max(a, n, k);
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Maximum unique from set: 7
Maximum unique from set: 7
Maximum unique from set: 5
raja
Published on 10-Feb-2020 09:32:52
Advertisements