D - Pyramid Editorial by evima

Another Solution

Let’s consider dividing the pyramid sequence into the left half (\(1, 2, \dots, k\): referred to as the left pyramid sequence of length \(k\)) and the right half (\(k, k-1, \dots, 1\): the right pyramid sequence of length \(k\)).

For each integer \(i\) \((1 \leq i \leq N)\), let \(l_i\) be the length of the longest left pyramid sequence ending with \(A_i\). (That is, \(A_{i-l_i+1}, A_{i-l_i+2}, \dots, A_i\) is a left pyramid sequence, but it would not be if \(A_{i-l_i}\) is added to the left end.) For convenience, let \(l_0 = 0\). Then, we have \(l_i = \min(A_i, l_{i-1} + 1)\), so we can calculate \(l_1, l_2, \dots, l_N\) in this order.

Similarly, for each integer \(i\) \((1 \leq i \leq N)\), let \(r_i\) be the length of the longest right pyramid sequence starting with \(A_i\). (That is, \(A_i, A_{i+1}, \dots, A_{i+r_i-1}\) is a right pyramid sequence, but it would not be if \(A_{i+r_i}\) is added to the right end.) For convenience, let \(r_{N+1} = 0\). Then, we have \(r_i = \min(A_i, r_{i+1} + 1)\), so we can calculate \(r_N, r_{N-1}, \dots, r_1\) in this order.

The answer to the problem is the largest among \(\min(l_1, r_1), \min(l_2, r_2), \dots, \min(l_N, r_N)\), which can be found in linear time.

Sample Implementation (Python)

N = int(input())
A = [0] + list(map(int, input().split()))

l, r = [0] * (N + 2), [0] * (N + 2)
for i in range(1, N + 1):
    l[i] = min(A[i], l[i - 1] + 1)
for i in range(N, 0, -1):
    r[i] = min(A[i], r[i + 1] + 1)
print(max(min(l[i], r[i]) for i in range(1, N + 1)))

posted:
last update: