#P1163B2. Cat Party (Hard Edition)
Cat Party (Hard Edition)
No submission language available for this problem.
Description
This problem is same as the previous one, but has larger constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the -th day has a ribbon with color . Shiro wants to know the largest number , such that if we consider the streak of the first days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining will have the same number of occurrences.
For example, consider the following sequence of : . Then makes a streak, since if we remove the leftmost , each ribbon color will appear exactly twice in the prefix of days. Note that doesn't form a streak, since you must remove exactly one day.
Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.
The first line contains a single integer () — the total number of days.
The second line contains integers () — the colors of the ribbons the cats wear.
Print a single integer — the largest possible streak of days.
Input
The first line contains a single integer () — the total number of days.
The second line contains integers () — the colors of the ribbons the cats wear.
Output
Print a single integer — the largest possible streak of days.
Samples
Note
In the first example, we can choose the longest streak of days, since upon removing the last day out of the streak, all of the remaining colors , , , and will have the same number of occurrences of . Note that the streak can also be days (by removing the -th day from this streak) but we are interested in the longest streak.
In the fourth example, if we take the streak of the first days, we can remove the third day from this streak then all of the remaining colors , , , and will occur exactly once.