Unique Snowflakes ⧉
The name of the game is keeping track of how many unique integers we've seen so far. This can be done with a set. The only remaining step is to discard any integers we saw before the first sighting of a repeated integer. To do this, we use a queue. Push new integers onto the back of the queue and add them to our set. If an integer is repeated, pop items from our queue until we find the first sighting of said integer, removing said items from our set as well. Do this for each test case and report on the maximum number of unique, consecutive integers we saw.
Time complexity is O(nlogn) because of the std::set. If we used a hash set, the complexity could be as low as O(n), provided the input data isn't devised to exploit std::hash.
_33#include <iostream>_33#include <queue>_33#include <set>_33using namespace std;_33int main () {_33 int t;_33 cin >> t;_33 while (t--) {_33 int n;_33 cin >> n;_33 set<int> seen;_33 queue<int> q;_33 int packageSize = 1;_33 while (n--) {_33 int x;_33 cin >> x;_33_33 if (seen.find(x) != seen.end()) {_33 while (q.front() != x) {_33 seen.erase(q.front());_33 q.pop();_33 }_33 q.pop(); // remove x_33 } else {_33 seen.insert(x);_33 }_33_33 q.push(x);_33 packageSize = max(packageSize, (int) q.size());_33 }_33 cout << packageSize << '\n';_33 }_33}
If you found this solution helpful, consider leaving a star!