Under construction

Still being built. Things may change

Cigle

Time limit1sMemory limit512 MB

Summary
Given bricks of fixed widths in a set order, build a zigzag wall that maximizes the number of points where four bricks touch.
Level

Hard8 of 10

Topics
Dynamic programming, Prefix sum
Solved
No attempts yet

Problem

In an alternate reality Earth 616, young Stjepan lives a totally different life. He is enrolled in a brick-crafting course at the School of Arts and Design. Like every child there, he is obsessed with patterns. For example, his homework requires him to build a brick wall using NN bricks. But he will not start building until he is satisfied with his two-dimensional sketch.

On the sketch, every brick is a rectangle with unit height and width did_i. He chooses the order of the bricks beforehand and starts sketching from the bottom-most row.

In the first row, he places some number of bricks from left to right. In the second row, he places bricks from right to left, and the first brick in the second row aligns with the last brick in the first row (their right edges align). Next, in the third row, he places bricks again from left to right. The first brick in the third row aligns with the last brick in the second row, but this time by the left edges. He continues this process until no bricks are left. He may build a wall with any number of rows.

Stjepan uses super cement, so a brick may be placed so that no other brick is directly underneath it. Beauty of the wall is the number of places where 4 bricks touch.

For a given order of bricks and their respective sizes, find the largest possible beauty of the wall.

Input

The first line contains the integer NN from the problem statement.

The second line contains NN integers did_i from the problem statement.

Output

Print the largest possible beauty of any wall that can be built.

Constraints

Let MM be the width of the widest brick. Unless otherwise specified, 1≤M≤50001 \le M \le 5000 holds.

Hint

The wall with beauty 4 for the third sample is shown below.

Examples3

  1. Example 1

    Input
    6
    2 2 2 1 1 2
    
    Expected output
    2
    
  2. Example 2

    Input
    13
    9 5 2 8 8 2 5 9 9 7 8 5 10
    
    Expected output
    5
    
  3. Example 3

    Input
    12
    5 5 2 3 2 1 1 5 5 2 5 1
    
    Expected output
    4