Under construction

Still being built. Things may change

Game

Time limit2sMemory limit512 MB

Summary
Choose the order in which balls are manually removed so chain reactions of merging equal neighbors delete as many other balls as possible; output that maximum count.
Level

Hard9 of 10

Topics
Dynamic programming, Stack, Simulation, Game theory
Solved
No attempts yet

Problem

Boyan is playing a computer game. In the beginning there are N balls arranged in a line. Each ball has a number written on it, so that every two consecutive balls have different numbers. The game consists of the following steps:

  1. The player removes a ball from the line.
  2. While there are consecutive balls with equal numbers, they are automatically removed from the line.
  3. If there are balls left in the line, go to step 1, otherwise the game ends.

The score is the number of balls that are automatically removed. The goal of the game is to maximize the score.

Let's see an example of a game with 6 balls with numbers {1, 2, 3, 2, 1, 5}.

  1. Boyan removes the ball with number 3. The balls left are {1, 2, 2, 1, 5}.
  2. Removing the consecutive balls with equal numbers we have {1, 2, 2, 1, 5} -> {1, 1, 5} -> {5}. The ball left is {5}.
  3. Since there are balls left, we go to step 1.
  1. Boyan removes the ball with number 5. The balls left are {}.
  2. There are no consecutive balls with equal numbers.
  3. There are no balls left, so the game ends.

The number of balls that are automatically removed is 4. It is the maximum possible score for this game. Boyan is playing a lot, but he is still not sure when he is playing optimally. Write program game to help him to find the best score he can achieve.

Input

The first line contains the positive integer N.

The second line contains N positive integers, the numbers written on the balls.

Output

Print the maximum possible score Boyan can achieve.

Constraints

  • 1 ≤ N ≤ 500
  • 1 ≤ number written on a ball ≤ 1 000 000

Examples2

  1. Example 1

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

    Input
    9
    1 5 1 3 2 4 2 3 1
    
    Expected output
    6