Redaksiya
Let the array store the identification numbers of the songs. Using two pointers, we will maintain a sliding window in which the songs do not repeat. In other words, all the songs in the segment are unique. The songs from this segment will be stored in a set . For each value of , we will try to extend the segment to the maximum possible length. That is, for a fixed , we will search for such a that in the segment the songs do not repeat, but in the segment duplicates already appear.
When processing the current song at index , there are two possible cases:
If the song is not present in the segment , add it to this segment, extending it to ;
If the song is already present in the segment, shift the left boundary to the right until disappears from the segment . Then, add to the segment, extending it to . With each shift of , remove the corresponding elements from the set ;
Among all possible segments with unique songs, find the maximum length. This will be the answer to the problem.
Example
Let’s consider how the segments with unique songs will change for the first example.
The length of the longest segment is .
Algorithm realization
Read the input data. The identification numbers of the songs are stored in the array .
scanf("%d", &n); v.resize(n); for (i = 0; i < n; i++) scanf("%d", &v[i]);
Maintain the segment of unique songs (i.e., the songs from to do not repeat). In the set , store the identification numbers of the songs from this segment. The variable tracks the length of the longest fragment with unique songs.
i = res = 0; for (j = 0; j < n; j++) {
Consider the current song at index . If it is already in the set , it will not be possible to extend the current segment by including the -th song. In this case, we need to shift the left boundary , removing the song from the set , until the -th song disappears from the set .
while (s.find(v[j]) != s.end()) { s.erase(v[i]); i++; }
Add the -th song to the segment and, accordingly, to the set . Thus, the segment will not contain any repeated songs.
s.insert(v[j]);
Among all possible segments , find the longest one. The length of the segment is .
res = max(res, j - i + 1); }
Print the answer.
printf("%d\n", res);