This page is still under construction.

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

Prime Scrabble

Interview

Time limit1sMemory limit1024 MB

Summary
Given up to 8 digit tiles, choose a placement order and direction to maximize the sum of prime-reading sums earned minus the values of unplaced tiles.
Level

Medium6 of 10

Topics
Brute force, Math, Backtracking, Number theory
Solved
No attempts yet

Problem

Prime Scrabble is a single-player tile game. You are given NN tiles, each showing a single digit from 11 to 99. The value of a tile equals the digit written on it.

You build one horizontal row of tiles. You start the row with a single tile, and on every later placement you extend the current row by adding one tile at its left end or its right end. Tiles already on the board are never rearranged.

Whenever the row currently on the board reads as a prime number from left to right, you immediately score points equal to the sum of the values of all tiles on the board. If it also reads as a prime number from right to left, you score that same amount once more. So a row that is prime in both reading directions scores twice the sum of its tiles at the moment it is completed, while a row that is prime in exactly one direction scores it once. (A single-digit prime, or any palindromic prime, reads as a prime in both directions and therefore scores twice.)

After your final placement, the resulting row must read as a prime in at least one direction. Every tile you never place stays in your hand, and each such tile subtracts its value from your score as a penalty. If no prime can be formed at all, you may place nothing and leave every tile in your hand.

A prime is an integer greater than 11 whose only divisors are 11 and itself. For example 2,3,5,72, 3, 5, 7 are primes, whereas 44 is divisible by 22 and 66 is divisible by both 22 and 33, so they are not.

Your total score is the sum of the points earned on your placements minus the total value of the tiles left in your hand. Find the maximum total score you can achieve.

Input

The first line contains the number of tiles NN (1≤N≤81 \le N \le 8). The second line contains NN space-separated integers, each between 11 and 99 (the digits on the tiles).

Output

Output a single integer: the maximum total score you can achieve. It equals the points earned from forming primes minus the total value of the tiles left in your hand, and it may be negative.

Examples2

  1. Example 1

    Input
    4
    1 6 5 7
    
    Expected output
    74
    
  2. Example 2

    Input
    4
    1 7 6 7
    
    Expected output
    48