Birthday

Time limit2sMemory limit64 MB

Summary
Children sit around a round table in order 1..n; reseat them into a given cyclic order while minimizing the largest distance anyone walks along the circle.
Level

Hard8 of 10

Topics
Binary search, Sorting, Math, Implementation
Solved
No attempts yet

Problem

It is Byteman's birthday today. There are nn children at his birthday party (Byteman included), numbered from 11 to nn. Byteman's parents have prepared a big round table with nn chairs around it.

The children sit down in order. Child 11 takes any seat. Child 22 takes the seat to the left, child 33 the next seat to the left, and so on, until child nn takes the last free seat, between child 11 and child n−1n-1.

Some children get noisy when they sit too close to certain others, so the parents want to reseat everyone into a specific cyclic order given by a permutation p1,p2,…,pnp_1, p_2, \ldots, p_n (distinct integers from 11 to nn): child p1p_1 must sit between pnp_n and p2p_2, child pip_i (for i=2,3,…,n−1i = 2, 3, \ldots, n-1) must sit between pi−1p_{i-1} and pi+1p_{i+1}, and child pnp_n must sit between pn−1p_{n-1} and p1p_1. Note that child p1p_1 may end up on either side of child pnp_n: the cyclic order can be realized in either rotational direction.

To reach the desired order, every child moves around the table some number of seats, either to the left or to the right; the parents choose a direction and a distance for each child. On a signal, all children stand up at once, walk to their new places, and sit down.

The mess of a reseating is the largest number of seats moved by any single child. Among all reseatings that produce the desired cyclic order, the parents want one with the smallest possible mess.

Write a program that reads nn and the target permutation and prints the minimum possible mess.

Input

The first line contains one integer nn (1≤n≤1061 \le n \le 10^6).

The second line contains nn integers p1,p2,…,pnp_1, p_2, \ldots, p_n separated by single spaces, forming a permutation of {1,2,…,n}\{1, 2, \ldots, n\} that describes the desired cyclic order of the children.

Output

Print a single integer: the minimum possible mess.

Hint

For n=6n = 6 and the target order 3 4 5 1 2 63\ 4\ 5\ 1\ 2\ 6, the left figure shows the initial seating. In one optimal reseating (middle figure), children 11 and 22 move one seat, children 33 and 55 move two seats, and children 44 and 66 stay put. The required order then holds: 33 sits between 66 and 44, 44 between 33 and 55, 55 between 44 and 11, 11 between 55 and 22, 22 between 11 and 66, and 66 between 22 and 33. Another optimal seating is shown on the right. In both, no child moves more than two seats, so the minimum mess is 22.

Examples2

  1. Example 1

    Input
    6
    3 4 5 1 2 6
    
    Expected output
    2
    
  2. Example 2

    Input
    5
    1 2 3 4 5
    
    Expected output
    0