This page is still under construction.

Parts of this page are still being built. What you see may change.

Make all numbers equal 2

Time limit2sMemory limit512 MB

Summary
Given a sequence where one Add raises a whole run of equal neighboring values by 1, find the minimum number of Adds to make all values equal.
Level

Medium5 of 10

Topics
Greedy, Implementation
Solved
No attempts yet

Problem

A sequence of nn natural numbers A[1],A[2],…,A[n]A[1], A[2], \dots, A[n] is given. The operation Add(i) raises A[i]A[i] by 1. It does not touch A[i]A[i] alone: the whole run of neighboring positions that currently hold the same value as A[i]A[i] goes up by 1 at once. A[1]A[1] and A[n]A[n] are not adjacent.

Look at the sequence {1, 1, 1, 1, 3, 3, 1}. Add(2) raises A[2]A[2] together with the equal values next to it and gives {2, 2, 2, 2, 3, 3, 1}. Add(4) then gives {3, 3, 3, 3, 3, 3, 1}, and Add(1) after that gives {4, 4, 4, 4, 4, 4, 1}.

You want to use the Add operation several times until A[1]=A[2]=⋯=A[n]A[1] = A[2] = \dots = A[n]. Find the smallest number of Add operations that is enough.

Input

The first line contains the integer nn. Each of the next nn lines contains one value, A[1]A[1] through A[n]A[n] in order.

1≤n≤1061 \le n \le 10^6, and every A[i]A[i] is a natural number no greater than 10910^9.

Output

Print the smallest number of Add operations on the first line.

Examples2

  1. Example 1

    Input
    3
    1
    5
    10
    
    Expected output
    9
    
  2. Example 2

    Input
    7
    1
    1
    1
    1
    3
    3
    1
    
    Expected output
    4