Official

D - Neq Neq Editorial by evima


If \(A_i=A_{i+1}\), Balls \(i\) and \(i+1\) will never disappear, so let us split the sequence here and consider the pieces independently.

Now, assume \(A_i \neq A_{i+1}\) (\(1 \leq i \leq N-1\)). Let us determine whether it is possible to keep only Balls \(1\) and \(N\). First of all, it is always possible when \(N=2,3\).

Now, assume \(N \geq 4\). The objective is obviously unachievable when there are just two different values. On the other hand, we will show that it is always achievable when there are three or more different values.

Let us prove it by induction on \(N\). The case \(N=4\) can be validated by hand. Now, let us assume that the statement holds true for \(N=K\) and show that it is also true for \(N=K+1\). Since there are three or more different values, there exists \(2 \leq i \leq N-1\) such that \(A_{i-1},A_{i},A_{i+1}\) are all different. If, after removing \(A_i\), there are still three or more different values, we are done. Otherwise, \(A\) has the form \(A=(\cdots,y,x,y,x,A_i,y,x,y,x\cdots)\), in which case we can remove \(A_{i-1}\) or \(A_{i+1}\) to still have three or more different values. This completes the proof.

Let us do DP using these characteristics. When \((A_i,A_{i+1}\cdots,A_j)\) satisfies the condition above, there should be a transition \(dp[i] \rightarrow dp[j]\). There are \(O(N^2)\) transitions, but the distribution of indices \(i\) and \(j\) satisfying the requirement of three or more different values forms intervals, so we can accelerate the DP with prefix sums. The complexity is \(O(N)\). Some implementation may take \(O(N \log N)\) time, which is also fine.

posted:
last update: