EQLZR - Editorial

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4

Author: nikhil_010309
Tester: raysh07
Editorialist: iceknight1093

DIFFICULTY:

TBD

PREREQUISITES:

None

PROBLEM:

You’re given an array A.
At most once, you can choose any subarray and increment all its elements by 1.

Find the maximum possible number of equal adjacent pairs in the array.

EXPLANATION:

Let’s call index i good if A_i = A_{i+1}.
Our objective is to maximize the number of good indices in the array.

Suppose we choose to increment the elements of the subarray A[L, R].
Observe that:

  • If L \gt 1 and index L-1 was good earlier, it will now become not good; since A_L changed.
    Similarly, if R \lt N and R was good, it will become not good.
  • On the other hand, if L \gt 1 and L-1 was not good earlier, it’s possible for L-1 to become good; if A_L becomes equal to A_{L-1} after the increment.
    Similarly, if R wasn’t good earlier, it might become good now if it equals A_{R+1}.
  • No other index can change its good-ness!
    • For L \le i \lt R, both A_i and A_{i+1} will increase by 1, so they’ll be equal afterwards iff they were equal to start with.
    • For i \lt L-1 and i \gt R, A_i and A_{i+1} don’t change at all.

Basically, only the good-ness of the indices L-1 and R can change at all; and the change at L-1 does not depend on the choice of R (and vice versa).


This gives us a fairly simple solution: iterate over R from left to right, while also maintaining the maximum “profit” so far from choosing some L \le R.
Then update the answer with the profit at R plus the maximum profit from L \le R.

TIME COMPLEXITY:

\mathcal{O}(N) per testcase.

CODE:

Editorialist's code (PyPy3)
for _ in range(int(input())):
    n = int(input())
    a = list(map(int, input().split()))
    
    base, add, mx = 0, 0, 0
    for i in range(n):
        if i+1 < n and a[i] == a[i+1]: base += 1
        
        if i > 0:
            if a[i-1] == a[i]+1: mx = 1
        
        if i+1 < n:
            if a[i]+1 == a[i+1]: add = max(add, 1+mx)
            elif a[i] == a[i+1]: add = max(add, -1+mx)
            else: add = max(add, mx)
        else: add = max(add, mx)
    print(base + add)
1 Like