Editorial
For each person , define
the index of the last message written by that person. The author condition is equivalent to .
Set and . Let be the number of people whose last read message is exactly . Then
The input guarantees that is non-increasing, so every is a nonnegative integer.
Let be the number of people satisfying . Only these people may have .
Choose the people with in increasing order of . Before processing , exactly
people have already received values smaller than . Every such person satisfies . Therefore, the number of unassigned people who may receive value is
We must choose exactly of them. Hence the answer is
The problem guarantees that at least one valid sequence exists, so every selection step is feasible. An implementation may still check whether an upper argument is negative or smaller than .
Compute every , count their frequencies, and take prefix sums to obtain all . With factorials and inverse factorials, each binomial coefficient is evaluated in constant time.
The time complexity is and the memory complexity is .