Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.

The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence.  The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105).

Print a single integer — the maximum number of points that Alex can earn.

NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points.

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.Array.Unboxed
import Data.List
import Data.Int

main = putStr . evalState app . B.words =<< B.getContents

app = show `fmap` solve `fmap` (flip replicateM poi =<< poi)
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve xs = snd $ foldl' (\(!prev, !curr) (x, f) -> (curr, max curr $ prev + fromIntegral x * fromIntegral f)) (0 :: Int64, fromIntegral $ snd $ head freq) $ tail freq
  where
  freq = assocs (accumArray (+) 0 (0, maximum xs) $ zip xs (repeat 1) :: UArray Int Int)

import Data.List
import qualified Data.Map as Map

count l = sort $ map (\g -> (head g, length g)) $ group (sort l)

g :: Integer -> Integer -> Int -> Map.Map Int Int -> Integer
g pprev prev i elems
  | i > (fst . Map.findMax) elems = max pprev prev
  | otherwise =
    let v = max prev (pprev + (fromIntegral i) * (fromIntegral $ Map.findWithDefault 0 i elems))
    in g prev v (i+1) elems

f :: [Int] -> Integer
f xs = g 0 0 0 (Map.fromList $ count xs)

main = interact $ show . f . (map read) . words . head . tail . lines

import Data.List

main :: IO()
main = print . solve . tail . map read . words =<< getContents

solve :: [Integer] -> Integer
solve a =
    let sa = sort a
    in  count (compress (tail sa) (head sa) 1) 0 0 0

compress :: [Integer] -> Integer -> Integer -> [(Integer, Integer)]
compress []     num cnt = [(num, cnt)]
compress (a:ax) num cnt | num == a  = compress ax num (cnt + 1)
                        | otherwise = (num, cnt):(compress ax a 1)

count :: [(Integer, Integer)] -> Integer -> Integer -> Integer -> Integer
count []             _    n y = max n y
count ((num, cnt):s) last n y | num == last + 1 = count s num (max n y) (n + num * cnt)
                              | otherwise       = count s num (max n y) ((max n y) + num * cnt)

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
import Data.Array
-- import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
-- import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

-- getInts = fmap (map read . words) getLine
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  getLine
  as <- getInts

  let
    cs = accumArray (+) 0 (1, 10^5) $ zip as $ repeat (1 :: Int64)

    r = listArray (0, 10^5) $ map f [0..10^5]
      where
        f 0 = 0
        f 1 = cs!1
        f i = max (r!(i-1)) (r!(i-2) + (fromIntegral i)*cs!i)

  print $ r!(10^5)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
inf = maxBound `div` 2 :: Int

main = do
    getLine
    as <- readInts
    print $ solve as

solve :: [Int] -> Int64
solve as = dp ! (10^5)
    where
    hist :: UArray Int Int64
    hist = accumArray (\x _ -> x+1) 0 (0,10^5) $ map (,()) as
    dp :: Array Int Int64
    dp = listArray (0,10^5) $ map f [0..10^5]
    f 0 = 0
    f 1 = hist ! 1
    f x | a == 0 = k1
        | otherwise = max k1 $ k2 + a * (fromIntegral x)
        where
        a = hist ! x
        k1 = dp ! (x-1)
        k2 = dp ! (x-2)

import Data.Array

main :: IO ()
main = do
  n <- readLn
  xs <- map read.words <$> getLine
  print $ solve n xs

solve :: Integer -> [Integer] -> Integer
solve _ xs = res!100000
  where
    arr = accumArray (+) 0 (1,100000) [(x,x)|x <- xs] :: Array Integer Integer
    res = listArray (0,100000) $ 0:(arr!1):[max (arr!i + res!(i-2)) (res!(i-1))| i <- [2..100000]] :: Array Integer Integer

import Control.Applicative
import Data.Array.IArray
import qualified Data.Foldable as F
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

main = do
    n <- readLn :: IO Int
    a <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine
    let s = accumArray (+) 0 (1, 10 ^ 5)  [(x, toInteger x) | x <- a] :: Array Int Integer
    let maxA = maximum a
    let dp = array (0, maxA) ((0, 0) : (1, s ! 1) : [(i, max (dp ! (i - 1)) ((dp ! (i - 2) ) + s ! i)) | i <- [2 .. maxA]]) :: Array Int Integer
    putStrLn . show . F.foldl1 max $ dp

import Data.List
import Data.Maybe
import Data.Char
import Data.Function
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.map read. words.head. tail.lines
solve :: [Integer]->String
solve xs = show $ head $ slv1 $ foldr f [] $ sort xs
  where
  f a []  = [[a,1]]
  f a ([b1,b2]:xs)  = if a==b1 then ([b1,b2+1]:xs) else [a,1]:([b1,b2]:xs)
slv1 xss =foldr f1 [] xss where
  f1 [a1,a2] [] = [a2*a1,0,1,a1]
  f1 [a1,a2] [sum1,prev,l,a] | l==0 && a-a1<=1 = [sum1+a2*a1,sum1,1,a1]
                             | l==1 && a-a1<=1 = if a2*a1+prev>sum1 then [a2*a1+prev,sum1,1,a1] else [sum1,0,0,a1]
                             | a-a1>1       = [a2*a1+sum1,sum1,1,a1]

import Control.Monad
import Data.Array
import Data.Char
import Data.Functor
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = map (read . B.unpack) . B.words <$> B.getLine
getIntList :: IO [Int]
getIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

-- best result only selecting numbers <= i
solve1 :: Array Int Int64 -> Int -> Int64
solve1 a = (r !)
    where r = listArray (0, 100000) (0 : a ! 1 : map f [2..100000])
          f i = max (r ! (i - 1)) (a ! i + r ! (i - 2))

(+^) :: Int64 -> Int -> Int64
a +^ b = a + fromIntegral b

solve :: [Int] -> Int64
solve a = solve1 cnt 100000
    where cnt = accumArray (+^) 0 (1, 100000) (zip a a)

main :: IO ()
main = getLine >> getIntList >>= print . solve

import Data.Array.MArray
import Data.Array.IO

type IntArray = IOArray Integer Integer

preProcess :: IO IntArray
preProcess = do
    count <- newArray (0, 100000) 0 :: IO IntArray
    getLine
    a <- (getLine >>= (return . map read . words))
    mapM_ (\x -> (readArray count x) >>= ((writeArray count x) . (+x))) a
    return count

solve :: [Integer] -> Integer
solve count = dp !! 100000
    where dp = 0 : (count!!1) : zipWith max (zipWith (+) dp (drop 2 count)) (tail dp)

main = do
    preProcess >>= getElems >>= (print . solve)

import Control.Applicative
import Control.Monad
import Data.List
import Data.Array

process::[(Integer,Integer)]->Integer
process q = dp!(100100)
   where qq = accumArray (+) 0 (1,100100) q
         dp =array (0,100100) ([(0,0),(1,qq!1)]
           ++ [(i,max (dp!(i-2)+qq!i) (dp!(i-1)))|i<-[2..100100]])

main=do
     getLine
     q<-  map (\z-> (head z,sum z)) <$> group <$> sort <$> map read <$> words <$>getLine ::IO [(Integer,Integer)]
     print $ process q

import Data.List

main = do
    getLine
    nums <- getLine
    print $ max_score $ map read $ words nums

add :: (a -> a -> Bool) -> a -> [[a]] -> [[a]]
add eq x ((y:ys):others) = if eq x y then (x:y:ys):others else [x]:(y:ys):others
add eq x [] = [[x]]

adjacentGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
adjacentGroupBy eq xs = foldr (add eq) [] xs

max_first :: [Integer] -> Integer
max_first (x:y:_) = max x y
max_first (x:_) = x
max_first [] = 0

safe_tail :: [a] -> [a]
safe_tail (_:xs) = xs
safe_tail [] = []

dp_step :: [Integer] -> (Integer, Integer) -> [Integer]
dp_step acc x = ((fst x * snd x) + (max_first $ safe_tail acc)):acc

group_score :: [(Integer, Integer)] -> Integer
group_score group =
    max_first dp
    where dp = foldl dp_step [] group

max_score :: [Integer] -> Integer
max_score nums =
    let
        pairs = map (\xs -> (head xs, toInteger $ length xs)) $ groupBy (==) $ sort nums
        groups = adjacentGroupBy (\x y -> (abs (fst x - fst y)) <= 1) pairs
    in
        sum $ map group_score groups

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Prelude hiding (interact, words, mconcat, mappend)

import qualified Data.ByteString.Lazy.Char8 as BS (empty)
import Data.ByteString.Lazy.Char8 (interact, words, readInt)
import Data.ByteString.Builder (toLazyByteString, int64Dec, char8)
import Data.Monoid (mconcat, mappend)

import Data.List (sort, group)
import Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)
import Control.Arrow ((&&&))
import Data.Int (Int64)

-- import Debug.Trace (trace)
-- mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x

main :: IO ()
main = interact $ showResultsBS . solveMany . parseIntsBS
    where
      parseIntsBS = map parseSingleInt . words  where
          parseSingleInt = unpackSingleInt . readInt
          unpackSingleInt (Just (num, rest))
              | (rest == BS.empty) = num
              | otherwise = error "Single word expected."
          unpackSingleInt _ = error "Error parsing readInt result."
      showResultsBS = toLazyByteString . mconcat . map resultBuilder  where
          resultBuilder = (flip mappend $ char8 '\n') . int64Dec
      solveMany [] = []
      solveMany (n:rest) = (solveTC $ n : take n rest) : (solveMany $ drop n rest)
      solveTC (n:listA) = solveFreqs . toFreqs n $ listA
      solveTC _ = error "Length and list are expected."

type ANum = Int  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int  -- number of elements in a[]

type FreqArray = Array ANum Cnt

-- Convert input data to an array of frequencies.
toFreqs :: Cnt -> [ANum] -> FreqArray
toFreqs _lenA listA = f
    where
      f = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA
      freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList
          where
            maxA = getNum . head $ assocList
            getNum (num,_cnt) = num

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (Show, Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (Show, Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqArray -> ASum
solveFreqs freqsArray = maxDP maxA  where
    maxA = snd . bounds $ freqsArray
    maxDP i = (max
               (dpMemo ! (i, Chosen,  presenceByNum i))
               (dpMemo ! (i, Removed, presenceByNum i)))
    countByNum num
        | num > 0 = freqsArray ! num
        | otherwise = 0
    presenceByNum = toPresence . countByNum
    toPresence count | count > 0 = Present | otherwise = Absent

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = maxDP (maxNum-2) + numsum maxNum
        f _      _       = maxDP (maxNum-1)
        numsum num = n * i  where
            n = fromIntegral num :: ASum
            i = fromIntegral $ countByNum num

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs show-res default all submit
default: all

all: run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary
run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -Wall -Wextra -std=c++0x -pedantic -Werror $+
./hs.exec: my-copied.hs
	ghc -Wall -Werror -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Prelude hiding (interact, words, mconcat, mappend)

import qualified Data.ByteString.Lazy.Char8 as BS (empty)
import Data.ByteString.Lazy.Char8 (interact, words, readInt)
import Data.ByteString.Builder (toLazyByteString, int64Dec, char8)
import Data.Monoid (mconcat, mappend)

import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HM

import Data.Array (Ix, (!), listArray, range)
import Data.Int (Int64)

-- import Debug.Trace (trace)
-- mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x

main :: IO ()
main = interact $ showResultsBS . solveMany . parseIntsBS
    where
      parseIntsBS = map parseSingleInt . words  where
          parseSingleInt = unpackSingleInt . readInt
          unpackSingleInt (Just (num, rest))
              | (rest == BS.empty) = num
              | otherwise = error "Single word expected."
          unpackSingleInt _ = error "Error parsing readInt result."
      showResultsBS = toLazyByteString . mconcat . map resultBuilder  where
          resultBuilder = (flip mappend $ char8 '\n') . int64Dec
      solveMany [] = []
      solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases)  where
          (thisCase, otherCases) = splitAt n rest

type ANum = Int  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int  -- number of elements in a[]

type Freqs = HashMap ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to an array of frequencies.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs (maximum listA)
    where
      freqs = HM.fromListWith incrSec [(num, 1) | num <- listA]
      incrSec _new = (+1)

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (Show, Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (Show, Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = maxDP maxA  where
    maxDP i = (max
               (dpMemo ! (i, Chosen,  presenceByNum i))
               (dpMemo ! (i, Removed, presenceByNum i)))
    countByNum = flip (HM.lookupDefault 0) freqs
    presenceByNum = toPresence . countByNum
    toPresence count | count > 0 = Present | otherwise = Absent

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = maxDP (maxNum-2) + numsum maxNum
        f _      _       = maxDP (maxNum-1)
        numsum num = n * i  where
            n = fromIntegral num :: ASum
            i = fromIntegral $ countByNum num

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs show-res default all submit
default: all

all: run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary
run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | time ./hs.exec | sha1sum --binary

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -Wall -Wextra -std=c++0x -pedantic -Werror $+
./hs.exec: my-copied.hs
	ghc -Wall -Werror -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
-- http://mivael.in.ua
--
-- Trying to create a suitable effective IO template to use in
-- competitive programming.  Code brevity is secondary this time.
-- First priority is fast adaptability of the template for specific
-- problems during contest.
--

import qualified Prelude as P
import Prelude (($), (.), (-), (+), (*),
                otherwise, Bool(True), Bool(False), error, const, undefined)
import System.IO (IO)
import qualified Data.List as L
import qualified Data.ByteString.Lazy.Builder as BB
import qualified Data.ByteString.Lazy.Char8 as BL8
import Data.ByteString.Lazy.Builder.ASCII (int64Dec)
import Data.Int (Int64)
import Data.Char (isSpace)
import Data.Maybe
import Data.Functor
import Data.Eq
import Data.Ord

import Data.Array (Ix, (!), listArray, accumArray, range, Array)

main :: IO ()
main = BL8.interact $ BL8.unlines . L.map (showResult . solveCase) . readCases

type ANum = Int64  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int64  -- number of elements in a[]

type Case = [Int64]
type Result = ASum

showResult :: Result -> BL8.ByteString
showResult = BB.toLazyByteString . int64Dec

readCases :: BL8.ByteString -> [Case]
readCases = L.unfoldr readCase

dropSpaces :: BL8.ByteString -> BL8.ByteString
dropSpaces = BL8.dropWhile isSpace

readInt64 :: BL8.ByteString -> Maybe (Int64, BL8.ByteString)
readInt64 bs = conv <$> BL8.readInteger (dropSpaces bs)  where
    conv (num, bsRest) = (P.fromIntegral num :: Int64, bsRest)

-- 'readN n f i s' is like 'f s' but reads n consequential elements
-- from s, not just one.
-- 'i s' == True iff s is an empty string.
-- 'readN 0 f i s' is Nothing if (i s == True),
-- otherwise, 'readN n f i s' is an error if (i s == True).
-- It is an error if it is impossible to read n elements form s.
readN :: P.Integral n =>
         n -> (s -> Maybe (m, s)) -> (s -> Bool) -> s -> Maybe ([m], s)
readN cnt readFunc nullFunc str = rn2 cnt str  where
    rn2 c s = rn c s (nullFunc s)
    rn 0 _ True  = Nothing
    rn 0 s False = Just ([], s)
    rn _ _ True  = error "Unexpected end of input."
    rn n s False = Just (firstElem : otherElems, strRest2)  where
        (firstElem, strRest) = fromJust (readFunc s)
        (otherElems, strRest2) = fromJust (rn2 (n-1) strRest)

readCase :: BL8.ByteString -> Maybe (Case, BL8.ByteString)
readCase bsWithSpaces
    | BL8.null bs = Nothing
    | otherwise = readN n readInt64 BL8.null bsRest
    where
      bs = dropSpaces bsWithSpaces
      (n, bsRest) = fromJust (readInt64 bs)

solveCase :: Case -> Result
solveCase = solveFreqs . toFreqs

type Freqs = Array ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to a num-->frequencies mapping.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs maxA
    where
      maxA = L.maximum listA
      freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]

-- Whether ANum is chosen.
data NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed  where
    calcDP i numChoice = prevDP + thisSum  where
        (iprev, thisSum) = param numChoice  where
            param Removed = (i-1,  0)
            param Chosen  = (i-2,  (freqs ! i) * i)
        prevDP = r $ freqs ! iprev  where
            r 0 = get Removed
            r _ = max (get Removed) (get Chosen)
            get choicePrev = dpMemo ! (iprev, choicePrev)
    dpMemo = listArray memoBounds [dp n c
                                   | (n, c) <- range memoBounds]
      where
        memoBounds = ((-1, Chosen),
                      (maxA, Removed))
        dp (-1) _ = 0
        dp   0  _ = 0
        dp maxNum numChoice = calcDP maxNum numChoice

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit
default: all

all: time-hs run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary

run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
time-cpp: ./a.out 10pow5shuffled.in.txt
	cat -- 10pow5shuffled.in.txt | time ./a.out

run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary
time-hs: ./hs.exec 10pow5shuffled.in.txt
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216
	time ./hs.exec +RTS -K16777216 < 10pow5shuffled.in.txt
	#time ./hs.exec +RTS -p -K16777216 < 10pow5shuffled.in.txt

10pow5shuffled.in.txt:
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt
	wc -l -- 10pow5shuffled.in.txt

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+
./hs.exec: my-copied.hs
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -o '$@' $+
	ghc -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs
/10pow5shuffled.in.txt

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Prelude hiding (interact, words)

import qualified Data.ByteString.Lazy.Char8 as BS (empty)
import Data.ByteString.Lazy.Char8 (interact, words, readInt)
import Data.ByteString.Lazy.Builder (toLazyByteString, char8)
import Data.ByteString.Lazy.Builder.ASCII (int64Dec)
import Data.Monoid (mconcat, mappend)

import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HM

import Data.Array (Ix, (!), listArray, accumArray, range)
import Data.Int (Int64)

-- import Debug.Trace (trace)
mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x
mytrace _s = id

type MyNum = Int64
type ANum = MyNum  -- elements of a[]
type ASum = MyNum  -- sum of ANum values
-- type ANum = Int64  -- elements of a[]
-- type ASum = Int64  -- sum of ANum values
type Cnt = Int64  -- number of elements in a[]

main :: IO ()
main = interact $ showResultsBS . solveMany . mytrace "input nums" . parseIntsBS
    where
      parseIntsBS = map parseSingleInt . words  where
          parseSingleInt = unpackSingleInt . readInt
          unpackSingleInt (Just (num, rest))
              | (rest == BS.empty) = fromIntegral num
              | otherwise = error "Single word expected."
          unpackSingleInt _ = error "Error parsing readInt result."
      showResultsBS = toLazyByteString . mconcat . map resultBuilder  where
          resultBuilder = (flip mappend $ char8 '\n') . int64Dec
      solveMany [] = mytrace "input nums" $ []
      solveMany (n:rest) = (solveFreqs . toFreqs . mytrace "this case" $ thisCase) : (solveMany otherCases)  where
          (thisCase, otherCases) = splitAt (fromIntegral n) rest

type Freqs = HashMap ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to an array of frequencies.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs (maximum listA)
    where
      freqs = HM.fromListWith incrSec [(num, 1) | num <- listA]
      incrSec _new = (+1)

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (
                          Show,  -- debug
                          Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (
                          Show,  -- debug
                          Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed  where
    calcDP i numChoice = f numChoice  where
        f Chosen  = maxDP (i-2) + (i * countByNum i)
        f Removed = maxDP (i-1)
        maxDP n = max (memo Chosen) (memo Removed)  where
            memo choice = dpMemo ! mytrace "dpMemo ind" (n, choice,  presence)
            presence
                | (cnt > 0) = Present
                | otherwise = Absent
            cnt = countByNum n

    -- countByNum = flip (HM.lookupDefault 0) freqs
    countByNum = (!) cbm . mytrace "countByNum arg"
    cbm = accumArray accfunc 0 (mytrace "cbm bounds" $ (-1,maxA)) (HM.toList freqs)  where
        accfunc 0 = id
        accfunc _ = error "HashMap with duplicates?"

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = calcDP maxNum Chosen
        f _      _       = calcDP maxNum Removed

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray (mytrace "dpMemo bounds" memoBounds) [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs show-res default all submit
default: all

all: run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary
run-cpp: ./a.out gen.in.txt
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } | time ./a.out
	cat -- gen.in.txt | ./a.out | sha1sum --binary
run-hs: ./hs.exec gen.in.txt
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } | time ./hs.exec +RTS -p -K100000000
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -Wall -Wextra -O3 -Werror $+
./hs.exec: my-copied.hs
	ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Data.List (sort, group)
import Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)
import Control.Arrow ((&&&))
import Data.Int (Int64)

-- import Debug.Trace (trace)
-- mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x

main :: IO ()
main = interact $ concat . map (++ "\n") . map show . solveMany . map read . words
    where
      solveMany [] = []
      solveMany (n:rest) = (solveTC $ n : take n rest) : (solveMany $ drop n rest)
      solveTC (n:listA) = solveFreqs . toFreqs n $ listA
      solveTC _ = error "Length and list are expected."

type ANum = Int  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int  -- number of elements in a[]

type FreqArray = Array ANum Cnt

-- Convert input data to an array of frequencies.
toFreqs :: Cnt -> [ANum] -> FreqArray
toFreqs lenA listA
    | (length listA /= lenA) = error "Wrong length."
    | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA
    where
      freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList
          where
            maxA = getNum . head $ assocList
            getNum (num,_cnt) = num

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (Show, Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (Show, Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqArray -> ASum
solveFreqs freqsArray = maxDP maxA  where
    maxA = snd . bounds $ freqsArray
    maxDP i = (max
               (dpMemo ! (i, Chosen,  presenceByNum i))
               (dpMemo ! (i, Removed, presenceByNum i)))
    countByNum num
        | num > 0 = freqsArray ! num
        | otherwise = 0
    presenceByNum = toPresence . countByNum
    toPresence count | count > 0 = Present | otherwise = Absent

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = maxDP (maxNum-2) + numsum  where
            numsum = n * i
            conv = (fromIntegral :: (Integral a => a -> Int64))
            n = conv maxNum
            i = conv $ countByNum maxNum
        f _      _       = maxDP (maxNum-1)

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
-- http://mivael.in.ua
--
-- Problem: 456C (Boredom)
-- http://codeforces.com/contest/456/problem/C
-- Codeforces Round #260 (Div. 2)
--
-- Trying to time-optimize a Haskell solution given that no mutable
-- types are used.
--

import Prelude
import Data.Array (Ix, (!), listArray, accumArray, range, Array)
import Data.Int (Int64)

type MyNum = Int64
type ANum = MyNum  -- elements of a[]
type ASum = MyNum  -- sum of ANum values
type Cnt = Int64  -- number of elements in a[]

main :: IO ()
main = interact $ unlines . map show . solveMany . map read . words
    where
      solveMany [] = []
      solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases)  where
          (thisCase, otherCases) = splitAt (fromIntegral n) rest

type Freqs = Array ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to a num-->frequencies mapping.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs maxA
    where
      maxA = maximum listA
      freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]

-- Whether ANum is chosen.
data NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed  where
    calcDP i numChoice = prevDP + thisSum  where
        (iprev, thisSum) = param numChoice  where
            param Removed = (i-1,  0)
            param Chosen  = (i-2,  (freqs ! i) * i)
        prevDP = r $ freqs ! iprev  where
            r 0 = get Removed
            r _ = max (get Removed) (get Chosen)
            get choicePrev = dpMemo ! (iprev, choicePrev)
    dpMemo = listArray memoBounds [dp n c
                                   | (n, c) <- range memoBounds]
      where
        memoBounds = ((-1, Chosen),
                      (maxA, Removed))
        dp (-1) _ = 0
        dp   0  _ = 0
        dp maxNum numChoice = calcDP maxNum numChoice

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit
default: all

all: time-hs run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary

run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
time-cpp: ./a.out 10pow5shuffled.in.txt
	cat -- 10pow5shuffled.in.txt | time ./a.out

run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary
time-hs: ./hs.exec 10pow5shuffled.in.txt
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000
	cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216

10pow5shuffled.in.txt:
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt
	wc -l -- 10pow5shuffled.in.txt

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+
./hs.exec: my-copied.hs
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+
	ghc -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs
/10pow5shuffled.in.txt

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
-- http://mivael.in.ua
--
-- Problem: 456C (Boredom)
-- http://codeforces.com/contest/456/problem/C
-- Codeforces Round #260 (Div. 2)
--
-- Trying to time-optimize a Haskell solution given that no mutable
-- types are used.
--

import Prelude hiding (interact, words)

import qualified Data.ByteString.Lazy.Char8 as BS (empty)
import Data.ByteString.Lazy.Char8 (interact, words, readInt)
import Data.ByteString.Lazy.Builder (toLazyByteString, char8)
import Data.ByteString.Lazy.Builder.ASCII (int64Dec)
import Data.Monoid (mconcat, mappend)

import Data.Array (Ix, (!), listArray, accumArray, range, Array, bounds, elems)
import Data.Int (Int64)

type MyNum = Int64
type ANum = MyNum  -- elements of a[]
type ASum = MyNum  -- sum of ANum values
type Cnt = Int64  -- number of elements in a[]

main :: IO ()
main = interact $ showResultsBS . solveMany . parseIntsBS
    where
      parseIntsBS = (map $ unpackSingleInt . readInt) . words  where
          unpackSingleInt (Just (num, rest))
              | (rest == BS.empty) = fromIntegral num
              | otherwise = error "Single word expected."
          unpackSingleInt _ = error "Error parsing readInt result."
      showResultsBS = toLazyByteString . mconcat . map resultBuilder  where
          resultBuilder = (flip mappend $ char8 '\n') . int64Dec
      solveMany [] = []
      solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases)  where
          (thisCase, otherCases) = splitAt (fromIntegral n) rest

type Freqs = Array ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to a num-->frequencies mapping.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs maxA
    where
      maxA = maximum listA
      freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]

-- Whether ANum is chosen.
data NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)
-- Whether ANum is present in a[].
data Presence = Present | Absent deriving (Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed  where
    calcDP i numChoice = f numChoice  where
        f Chosen  = maxDP (i-2) + (i * freqs ! i)
        f Removed = maxDP (i-1)
        maxDP n = max (memo Chosen) (memo Removed)  where
            memo choice = dpMemo ! (n, choice,  presenceByNum ! n)

    presenceByNum = listArray (bounds freqs) presenceList  where
        presence c | (c > 0) = Present | otherwise = Absent
        presenceList = [presence cnt | cnt <- elems freqs]

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = calcDP maxNum Chosen
        f _      _       = calcDP maxNum Removed

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit
default: all

all: time-hs run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary

run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
time-cpp: ./a.out 10pow5shuffled.in.txt
	cat -- 10pow5shuffled.in.txt | time ./a.out

run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary
time-hs: ./hs.exec 10pow5shuffled.in.txt
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000
	cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216

10pow5shuffled.in.txt:
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt
	wc -l -- 10pow5shuffled.in.txt

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+
./hs.exec: my-copied.hs
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+
	ghc -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs
/10pow5shuffled.in.txt

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
-- http://mivael.in.ua
--
-- Problem: 456C (Boredom)
-- http://codeforces.com/contest/456/problem/C
-- Codeforces Round #260 (Div. 2)
--
-- Trying to time-optimize a Haskell solution given that no mutable
-- types are used.
--

import Prelude hiding (interact, words)

import qualified Data.ByteString.Lazy.Char8 as BS (empty)
import Data.ByteString.Lazy.Char8 (interact, words, readInt)
import Data.ByteString.Lazy.Builder (toLazyByteString, char8)
import Data.ByteString.Lazy.Builder.ASCII (int64Dec)
import Data.Monoid (mconcat, mappend)

import Data.Array (Ix, (!), listArray, accumArray, range, Array)
import Data.Int (Int64)

type MyNum = Int64
type ANum = MyNum  -- elements of a[]
type ASum = MyNum  -- sum of ANum values
type Cnt = Int64  -- number of elements in a[]

main :: IO ()
main = interact $ showResultsBS . solveMany . parseIntsBS
    where
      parseIntsBS = (map $ unpackSingleInt . readInt) . words  where
          unpackSingleInt (Just (num, rest))
              | (rest == BS.empty) = fromIntegral num
              | otherwise = error "Single word expected."
          unpackSingleInt _ = error "Error parsing readInt result."
      showResultsBS = toLazyByteString . mconcat . map resultBuilder  where
          resultBuilder = (flip mappend $ char8 '\n') . int64Dec
      solveMany [] = []
      solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases)  where
          (thisCase, otherCases) = splitAt (fromIntegral n) rest

type Freqs = Array ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to a num-->frequencies mapping.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs maxA
    where
      maxA = maximum listA
      freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]

-- Whether ANum is chosen.
data NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed  where
    calcDP i numChoice = prevDP + thisSum  where
        (iprev, thisSum) = param numChoice  where
            param Removed = (i-1,  0)
            param Chosen  = (i-2,  (freqs ! i) * i)
        prevDP = r $ freqs ! iprev  where
            r 0 = get Removed
            r _ = max (get Removed) (get Chosen)
            get choicePrev = dpMemo ! (iprev, choicePrev)
    dpMemo = listArray memoBounds [dp n c
                                   | (n, c) <- range memoBounds]
      where
        memoBounds = ((-1, Chosen),
                      (maxA, Removed))
        dp (-1) _ = 0
        dp   0  _ = 0
        dp maxNum numChoice = calcDP maxNum numChoice

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit
default: all

all: time-hs run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary

run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
time-cpp: ./a.out 10pow5shuffled.in.txt
	cat -- 10pow5shuffled.in.txt | time ./a.out

run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary
time-hs: ./hs.exec 10pow5shuffled.in.txt
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000
	cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216

10pow5shuffled.in.txt:
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt
	wc -l -- 10pow5shuffled.in.txt

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+
./hs.exec: my-copied.hs
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+
	ghc -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs
/10pow5shuffled.in.txt

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Prelude hiding (interact, words, mconcat, mappend)

import qualified Data.ByteString.Lazy.Char8 as BS (empty)
import Data.ByteString.Lazy.Char8 (interact, words, readInt)
import Data.ByteString.Builder (toLazyByteString, int64Dec, char8)
import Data.Monoid (mconcat, mappend)

import Data.List (sort, group)
import Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)
import Control.Arrow ((&&&))
import Data.Int (Int64)

-- import Debug.Trace (trace)
-- mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x

main :: IO ()
main = interact $ showResultsBS . solveMany . parseIntsBS
    where
      parseIntsBS = map parseSingleInt . words  where
          parseSingleInt = unpackSingleInt . readInt
          unpackSingleInt (Just (num, rest))
              | (rest == BS.empty) = num
              | otherwise = error "Single word expected."
          unpackSingleInt _ = error "Error parsing readInt result."
      showResultsBS = toLazyByteString . mconcat . map resultBuilder  where
          resultBuilder = (flip mappend $ char8 '\n') . int64Dec
      solveMany [] = []
      solveMany (n:rest) = (solveTC $ n : thisCase) : (solveMany otherCases)  where
          (thisCase, otherCases) = splitAt n rest
      solveTC (n:listA) = solveFreqs . toFreqs n $ listA
      solveTC _ = error "Length and list are expected."

type ANum = Int  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int  -- number of elements in a[]

type FreqArray = Array ANum Cnt

-- Convert input data to an array of frequencies.
toFreqs :: Cnt -> [ANum] -> FreqArray
toFreqs _lenA listA = f
    where
      f = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA
      freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList
          where
            maxA = getNum . head $ assocList
            getNum (num,_cnt) = num

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (Show, Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (Show, Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqArray -> ASum
solveFreqs freqsArray = maxDP maxA  where
    maxA = snd . bounds $ freqsArray
    maxDP i = (max
               (dpMemo ! (i, Chosen,  presenceByNum i))
               (dpMemo ! (i, Removed, presenceByNum i)))
    countByNum num
        | num > 0 = freqsArray ! num
        | otherwise = 0
    presenceByNum = toPresence . countByNum
    toPresence count | count > 0 = Present | otherwise = Absent

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = maxDP (maxNum-2) + numsum maxNum
        f _      _       = maxDP (maxNum-1)
        numsum num = n * i  where
            n = fromIntegral num :: ASum
            i = fromIntegral $ countByNum num

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs show-res default all submit
default: all

all: run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary
run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -Wall -Wextra -std=c++0x -pedantic -Werror $+
./hs.exec: my-copied.hs
	ghc -Wall -Werror -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Prelude hiding (interact, words)

import qualified Data.ByteString.Lazy.Char8 as BS (empty)
import Data.ByteString.Lazy.Char8 (interact, words, readInt)
import Data.ByteString.Lazy.Builder (toLazyByteString, char8)
import Data.ByteString.Lazy.Builder.ASCII (int64Dec)
import Data.Monoid (mconcat, mappend)

import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HM

import Data.Array (Ix, (!), listArray, range)
import Data.Int (Int64)

-- import Debug.Trace (trace)
-- mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x

main :: IO ()
main = interact $ showResultsBS . solveMany . parseIntsBS
    where
      parseIntsBS = map parseSingleInt . words  where
          parseSingleInt = unpackSingleInt . readInt
          unpackSingleInt (Just (num, rest))
              | (rest == BS.empty) = num
              | otherwise = error "Single word expected."
          unpackSingleInt _ = error "Error parsing readInt result."
      showResultsBS = toLazyByteString . mconcat . map resultBuilder  where
          resultBuilder = (flip mappend $ char8 '\n') . int64Dec
      solveMany [] = []
      solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases)  where
          (thisCase, otherCases) = splitAt n rest

type ANum = Int  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int  -- number of elements in a[]

type Freqs = HashMap ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to an array of frequencies.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs (maximum listA)
    where
      freqs = HM.fromListWith incrSec [(num, 1) | num <- listA]
      incrSec _new = (+1)

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (Show, Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (Show, Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = maxDP maxA  where
    maxDP i = (max
               (dpMemo ! (i, Chosen,  presenceByNum i))
               (dpMemo ! (i, Removed, presenceByNum i)))
    countByNum = flip (HM.lookupDefault 0) freqs
    presenceByNum = toPresence . countByNum
    toPresence count | count > 0 = Present | otherwise = Absent

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = maxDP (maxNum-2) + numsum maxNum
        f _      _       = maxDP (maxNum-1)
        numsum num = n * i  where
            n = fromIntegral num :: ASum
            i = fromIntegral $ countByNum num

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs show-res default all submit
default: all

all: run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary
run-cpp: ./a.out gen.in.txt
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } | time ./a.out | sha1sum --binary
	cat -- gen.in.txt | ./a.out | sha1sum --binary
run-hs: ./hs.exec gen.in.txt
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } | time ./hs.exec +RTS -p -K100000000 | sha1sum --binary
	cat -- gen.in.txt | time ./hs.exec | sha1sum --binary

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -Wall -Wextra -O3 -Werror $+
./hs.exec: my-copied.hs
	ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 3
    print("maxN = {!r}." . format(maxN))
    maxA = 3
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
-- http://mivael.in.ua
--

import qualified Prelude as P
import Prelude (($), (.), (-), (+), (*),
                otherwise, Bool(True), Bool(False), error, const, undefined)
import System.IO (IO)
import qualified Data.List as L
import qualified Data.ByteString.Lazy.Builder as BB
import qualified Data.ByteString.Lazy.Char8 as BL8
import Data.ByteString.Lazy.Builder.ASCII (int64Dec)
import Data.Int (Int64)
import Data.Char (isSpace)
import Data.Maybe
import Data.Functor
import Data.Eq
import Data.Ord

import Data.Array (Ix, (!), listArray, accumArray, range, Array)

main :: IO ()
main = BL8.interact $ BL8.unlines . L.map (showResult . solveCase) . readCases
    where
      showResult = BB.toLazyByteString . int64Dec
      readCases = L.unfoldr readCase

type ANum = Int64  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int64  -- number of elements in a[]

type Case = [Int64]
type Result = ASum

dropSpaces :: BL8.ByteString -> BL8.ByteString
dropSpaces = BL8.dropWhile isSpace

readInt64 :: BL8.ByteString -> Maybe (Int64, BL8.ByteString)
readInt64 bs = conv <$> BL8.readInteger (dropSpaces bs)  where
    conv (num, bsRest) = (P.fromIntegral num :: Int64, bsRest)

-- 'readN n f i s' is like 'f s' but reads n consequential elements
-- from s, not just one.
-- 'i s' == True iff s is an empty string.
-- 'readN 0 f i s' is Nothing if (i s == True),
-- otherwise, 'readN n f i s' is an error if (i s == True).
-- It is an error if it is impossible to read n elements form s.
readN :: P.Integral n =>
         n -> (s -> Maybe (m, s)) -> (s -> Bool) -> s -> Maybe ([m], s)
readN cnt readFunc nullFunc str = rn2 cnt str  where
    rn2 c s = rn c s (nullFunc s)
    rn 0 _ True  = Nothing
    rn 0 s False = Just ([], s)
    rn n s _     = Just (firstElem : otherElems, strRest2)  where
        (firstElem, strRest) = fromJust (readFunc s)
        (otherElems, strRest2) = unpack $ rn2 (n-1) strRest
        unpack Nothing    = ([], strRest)
        unpack (Just res) = res

readCase :: BL8.ByteString -> Maybe (Case, BL8.ByteString)
readCase bsWithSpaces
    | BL8.null bs = Nothing
    | otherwise = readN n readInt64 BL8.null bsRest
    where
      bs = dropSpaces bsWithSpaces
      (n, bsRest) = fromJust (readInt64 bs)

solveCase :: Case -> Result
solveCase = solveFreqs . toFreqs

type Freqs = Array ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to a num-->frequencies mapping.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs maxA
    where
      maxA = L.maximum listA
      freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]

-- Whether ANum is chosen.
data NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed  where
    calcDP i numChoice = prevDP + thisSum  where
        (iprev, thisSum) = param numChoice  where
            param Removed = (i-1,  0)
            param Chosen  = (i-2,  (freqs ! i) * i)
        prevDP = r $ freqs ! iprev  where
            r 0 = get Removed
            r _ = max (get Removed) (get Chosen)
            get choicePrev = dpMemo ! (iprev, choicePrev)
    dpMemo = listArray memoBounds [dp n c
                                   | (n, c) <- range memoBounds]
      where
        memoBounds = ((-1, Chosen),
                      (maxA, Removed))
        dp (-1) _ = 0
        dp   0  _ = 0
        dp maxNum numChoice = calcDP maxNum numChoice

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit
default: all

all: time-hs run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary

run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
time-cpp: ./a.out 10pow5shuffled.in.txt
	cat -- 10pow5shuffled.in.txt | time ./a.out

run-hs: ./hs.exec gen.in.txt
	printf '1\n57' | ./hs.exec
	printf '1\n57\n' | ./hs.exec
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary
time-hs: ./hs.exec 10pow5shuffled.in.txt
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216
	time ./hs.exec +RTS -K16777216 < 10pow5shuffled.in.txt
	#time ./hs.exec +RTS -p -K16777216 < 10pow5shuffled.in.txt

10pow5shuffled.in.txt:
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt
	wc -l -- 10pow5shuffled.in.txt

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+
./hs.exec: my-copied.hs
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -o '$@' $+
	ghc -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs
/10pow5shuffled.in.txt

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
-- http://mivael.in.ua
--
-- Trying to create a suitable effective IO template to use in
-- competitive programming.  Code brevity is secondary this time.
-- First priority is fast adaptability of the template for specific
-- problems during contest.
--

import qualified Prelude as P
import Prelude (($), (.), (-), (+), (*),
                otherwise, Bool(True), Bool(False), error, const, undefined)
import System.IO (IO)
import qualified Data.List as L
import qualified Data.ByteString.Lazy.Builder as BB
import qualified Data.ByteString.Lazy.Char8 as BL8
import Data.ByteString.Lazy.Builder.ASCII (int64Dec)
import Data.Int (Int64)
import Data.Char (isSpace)
import Data.Maybe
import Data.Functor
import Data.Eq
import Data.Ord
import Data.Monoid (mappend, mconcat)

import Data.Array (Ix, (!), listArray, accumArray, range, Array)

main :: IO ()
-- main = BL8.interact $ BL8.unlines . L.map (showResult . solveCase) . readCases
main = BL8.interact $ showResultsBS . L.map solveCase . readCases  where
      showResultsBS = BB.toLazyByteString . mconcat . L.map resultBuilder  where
          resultBuilder = (P.flip mappend $ BB.char8 '\n') . int64Dec

type ANum = Int64  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int64  -- number of elements in a[]

type Case = [Int64]
type Result = ASum

-- showResult :: Result -> BL8.ByteString
-- showResult = BB.toLazyByteString . int64Dec

readCases :: BL8.ByteString -> [Case]
readCases = L.unfoldr readCase

dropSpaces :: BL8.ByteString -> BL8.ByteString
dropSpaces = BL8.dropWhile isSpace

readInt64 :: BL8.ByteString -> Maybe (Int64, BL8.ByteString)
readInt64 bs = conv <$> BL8.readInteger (dropSpaces bs)  where
    conv (num, bsRest) = (P.fromIntegral num :: Int64, bsRest)

-- 'readN n f i s' is like 'f s' but reads n consequential elements
-- from s, not just one.
-- 'i s' == True iff s is an empty string.
-- 'readN 0 f i s' is Nothing if (i s == True),
-- otherwise, 'readN n f i s' is an error if (i s == True).
-- It is an error if it is impossible to read n elements form s.
readN :: P.Integral n =>
         n -> (s -> Maybe (m, s)) -> (s -> Bool) -> s -> Maybe ([m], s)
readN cnt readFunc nullFunc str = rn2 cnt str  where
    rn2 c s = rn c s (nullFunc s)
    rn 0 _ True  = Nothing
    rn 0 s False = Just ([], s)
    rn _ _ True  = error "Unexpected end of input."
    rn n s False = Just (firstElem : otherElems, strRest2)  where
        (firstElem, strRest) = fromJust (readFunc s)
        (otherElems, strRest2) = fromJust (rn2 (n-1) strRest)

readCase :: BL8.ByteString -> Maybe (Case, BL8.ByteString)
readCase bsWithSpaces
    | BL8.null bs = Nothing
    | otherwise = readN n readInt64 BL8.null bsRest
    where
      bs = dropSpaces bsWithSpaces
      (n, bsRest) = fromJust (readInt64 bs)

solveCase :: Case -> Result
solveCase = solveFreqs . toFreqs

type Freqs = Array ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to a num-->frequencies mapping.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs maxA
    where
      maxA = L.maximum listA
      freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]

-- Whether ANum is chosen.
data NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed  where
    calcDP i numChoice = prevDP + thisSum  where
        (iprev, thisSum) = param numChoice  where
            param Removed = (i-1,  0)
            param Chosen  = (i-2,  (freqs ! i) * i)
        prevDP = r $ freqs ! iprev  where
            r 0 = get Removed
            r _ = max (get Removed) (get Chosen)
            get choicePrev = dpMemo ! (iprev, choicePrev)
    dpMemo = listArray memoBounds [dp n c
                                   | (n, c) <- range memoBounds]
      where
        memoBounds = ((-1, Chosen),
                      (maxA, Removed))
        dp (-1) _ = 0
        dp   0  _ = 0
        dp maxNum numChoice = calcDP maxNum numChoice

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit
default: all

all: time-hs run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary

run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
time-cpp: ./a.out 10pow5shuffled.in.txt
	cat -- 10pow5shuffled.in.txt | time ./a.out

run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary
time-hs: ./hs.exec 10pow5shuffled.in.txt
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216
	time ./hs.exec +RTS -K16777216 < 10pow5shuffled.in.txt
	#time ./hs.exec +RTS -p -K16777216 < 10pow5shuffled.in.txt

10pow5shuffled.in.txt:
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt
	wc -l -- 10pow5shuffled.in.txt

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+
./hs.exec: my-copied.hs
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -o '$@' $+
	ghc -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs
/10pow5shuffled.in.txt

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Prelude hiding (interact, words)

import qualified Data.ByteString.Lazy.Char8 as BS (empty)
import Data.ByteString.Lazy.Char8 (interact, words, readInt)
import Data.ByteString.Lazy.Builder (toLazyByteString, char8)
import Data.ByteString.Lazy.Builder.ASCII (int64Dec)
import Data.Monoid (mconcat, mappend)

-- import Data.HashMap.Lazy (HashMap)
-- import qualified Data.HashMap.Lazy as HM

import Data.Array (Ix, (!), listArray, accumArray, range, Array)
import Data.Int (Int64)

-- import Debug.Trace (trace)
mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x
mytrace _s = id

type MyNum = Int64
type ANum = MyNum  -- elements of a[]
type ASum = MyNum  -- sum of ANum values
-- type ANum = Int64  -- elements of a[]
-- type ASum = Int64  -- sum of ANum values
type Cnt = Int64  -- number of elements in a[]

main :: IO ()
main = interact $ showResultsBS . solveMany . mytrace "input nums" . parseIntsBS
    where
      parseIntsBS = map parseSingleInt . words  where
          parseSingleInt = unpackSingleInt . readInt
          unpackSingleInt (Just (num, rest))
              | (rest == BS.empty) = fromIntegral num
              | otherwise = error "Single word expected."
          unpackSingleInt _ = error "Error parsing readInt result."
      showResultsBS = toLazyByteString . mconcat . map resultBuilder  where
          resultBuilder = (flip mappend $ char8 '\n') . int64Dec
      solveMany [] = mytrace "input nums" $ []
      solveMany (n:rest) = (solveFreqs . toFreqs . mytrace "this case" $ thisCase) : (solveMany otherCases)  where
          (thisCase, otherCases) = splitAt (fromIntegral n) rest

-- type Freqs = HashMap ANum Cnt
type Freqs = Array ANum Cnt

data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to an array of frequencies.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs maxA
    where
      maxA = maximum listA
      -- freqs = HM.fromListWith incrSec [(num, 1) | num <- listA]
      -- incrSec _new = (+1)
      freqs = accumArray (+) 0 (-1,maxA) [(num, 1) | num <- listA]

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (
                          Show,  -- debug
                          Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (
                          Show,  -- debug
                          Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed  where
    calcDP i numChoice = f numChoice  where
        f Chosen  = maxDP (i-2) + (i * countByNum i)
        f Removed = maxDP (i-1)
        maxDP n = max (memo Chosen) (memo Removed)  where
            memo choice = dpMemo ! mytrace "dpMemo ind" (n, choice,  presence)
            presence
                | (cnt > 0) = Present
                | otherwise = Absent
            cnt = countByNum n

    -- countByNum = flip (HM.lookupDefault 0) freqs
    -- countByNum = (!) cbm . mytrace "countByNum arg"  where
    --     cbm = accumArray accfunc 0 (mytrace "cbm bounds" $ (-1,maxA)) (HM.toList freqs)
    --       where
    --         accfunc 0 = id
    --         accfunc _ = error "HashMap with duplicates?"
    countByNum = (!) freqs

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = calcDP maxNum Chosen
        f _      _       = calcDP maxNum Removed

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray (mytrace "dpMemo bounds" memoBounds) [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit
default: all

all: time-hs run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary

run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
time-cpp: ./a.out gen.in.txt
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } | time ./a.out

run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary
time-hs: ./hs.exec gen.in.txt
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } | time ./hs.exec +RTS -p -K100000000

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -Wall -Wextra -O3 -Werror $+
./hs.exec: my-copied.hs
	ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Data.List (sort, group)
import Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)
import Control.Arrow ((&&&))
import Data.Int (Int64)

-- import Debug.Trace (trace)
-- mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x

main :: IO ()
main = interact $ concat . map (++ "\n") . map show . solveMany . map read . words
    where
      solveMany [] = []
      solveMany (n:rest) = (solveTC $ n : take n rest) : (solveMany $ drop n rest)
      solveTC (n:listA) = solveFreqs . toFreqs n $ listA
      solveTC _ = error "Length and list are expected."

type ANum = Int  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int  -- number of elements in a[]

type FreqArray = Array ANum Cnt

-- Convert input data to an array of frequencies.
toFreqs :: Cnt -> [ANum] -> FreqArray
toFreqs lenA listA
    | (length listA /= lenA) = error "Wrong length."
    | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA
    where
      freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList
          where
            maxA = getNum . head $ assocList
            getNum (num,_cnt) = num

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (Show, Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (Show, Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqArray -> ASum
solveFreqs freqsArray = maxDP maxA  where
    maxA = snd . bounds $ freqsArray
    maxDP i = (max
               (dpMemo ! (i, Chosen,  presenceByNum i))
               (dpMemo ! (i, Removed, presenceByNum i)))
    countByNum num
        | num > 0 = freqsArray ! num
        | otherwise = 0
    presenceByNum = toPresence . countByNum
    toPresence count | count > 0 = Present | otherwise = Absent

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = maxDP (maxNum-2) + numsum maxNum
        f _      _       = maxDP (maxNum-1)
        numsum num = n * i  where
            n = fromIntegral num :: ASum
            i = fromIntegral $ countByNum num

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs show-res default all submit
default: all

all: run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary
run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -Wall -Wextra -std=c++0x -pedantic -Werror $+
./hs.exec: my-copied.hs
	ghc -Wall -Werror -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Prelude hiding (interact, words, mconcat, mappend)

import qualified Data.ByteString.Lazy.Char8 as BS (empty)
import Data.ByteString.Lazy.Char8 (interact, words, readInt)
import Data.ByteString.Builder (toLazyByteString, int64Dec, char8)
import Data.Monoid (mconcat, mappend)

import Data.List (sort, group)
import Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)
import Control.Arrow ((&&&))
import Data.Int (Int64)

-- import Debug.Trace (trace)
-- mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x

main :: IO ()
main = interact $ showResultsBS . solveMany . parseCasesBS
    where
      parseCasesBS = map parseSingleInt . words  where
          parseSingleInt = unpackSingleInt . readInt
          unpackSingleInt (Just (num, rest))
              | (rest == BS.empty) = num
              | otherwise = error "Single word expected."
          unpackSingleInt _ = error "Error parsing readInt result."
      showResultsBS = toLazyByteString . mconcat . map resultBuilder  where
          resultBuilder = (flip mappend $ char8 '\n') . int64Dec
      solveMany [] = []
      solveMany (n:rest) = (solveTC $ n : take n rest) : (solveMany $ drop n rest)
      solveTC (n:listA) = solveFreqs . toFreqs n $ listA
      solveTC _ = error "Length and list are expected."

type ANum = Int  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int  -- number of elements in a[]

type FreqArray = Array ANum Cnt

-- Convert input data to an array of frequencies.
toFreqs :: Cnt -> [ANum] -> FreqArray
toFreqs lenA listA
    | (length listA /= lenA) = error "Wrong length."
    | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA
    where
      freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList
          where
            maxA = getNum . head $ assocList
            getNum (num,_cnt) = num

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (Show, Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (Show, Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqArray -> ASum
solveFreqs freqsArray = maxDP maxA  where
    maxA = snd . bounds $ freqsArray
    maxDP i = (max
               (dpMemo ! (i, Chosen,  presenceByNum i))
               (dpMemo ! (i, Removed, presenceByNum i)))
    countByNum num
        | num > 0 = freqsArray ! num
        | otherwise = 0
    presenceByNum = toPresence . countByNum
    toPresence count | count > 0 = Present | otherwise = Absent

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = maxDP (maxNum-2) + numsum maxNum
        f _      _       = maxDP (maxNum-1)
        numsum num = n * i  where
            n = fromIntegral num :: ASum
            i = fromIntegral $ countByNum num

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs show-res default all submit
default: all

all: run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary
run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -Wall -Wextra -std=c++0x -pedantic -Werror $+
./hs.exec: my-copied.hs
	ghc -Wall -Werror -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
-- http://mivael.in.ua
--
-- Problem: 456C (Boredom)
-- http://codeforces.com/contest/456/problem/C
-- Codeforces Round #260 (Div. 2)
--
-- Trying to time-optimize a Haskell solution given that no mutable
-- types are used.
--

import Prelude hiding (interact, words)

import qualified Data.ByteString.Lazy.Char8 as BS (empty)
import Data.ByteString.Lazy.Char8 (interact, words, readInt)
import Data.ByteString.Lazy.Builder (toLazyByteString, char8)
import Data.ByteString.Lazy.Builder.ASCII (int64Dec)
import Data.Monoid (mconcat, mappend)

import Data.Array (Ix, (!), listArray, accumArray, range, Array, bounds, elems)
import Data.Int (Int64)

type MyNum = Int64
type ANum = MyNum  -- elements of a[]
type ASum = MyNum  -- sum of ANum values
type Cnt = Int64  -- number of elements in a[]

main :: IO ()
main = interact $ showResultsBS . solveMany . parseIntsBS
    where
      parseIntsBS = (map $ unpackSingleInt . readInt) . words  where
          unpackSingleInt (Just (num, rest))
              | (rest == BS.empty) = fromIntegral num
              | otherwise = error "Single word expected."
          unpackSingleInt _ = error "Error parsing readInt result."
      showResultsBS = toLazyByteString . mconcat . map resultBuilder  where
          resultBuilder = (flip mappend $ char8 '\n') . int64Dec
      solveMany [] = []
      solveMany (n:rest) = (solveFreqs . toFreqs $ thisCase) : (solveMany otherCases)  where
          (thisCase, otherCases) = splitAt (fromIntegral n) rest

type Freqs = Array ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to a num-->frequencies mapping.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs maxA
    where
      maxA = maximum listA
      freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]

-- Whether ANum is chosen.
data NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)
-- Whether ANum is present in a[].
data Presence = Present | Absent deriving (Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed  where
    calcDP i numChoice = f numChoice  where
        f Chosen  = maxDP (i-2) + (i * freqs ! i)
        f Removed = maxDP (i-1)
        maxDP n = max (memo Chosen) (memo Removed)  where
            memo choice = elemByInd  where
                elemByInd = dpMemo ! memoInd
                memoInd = (n, choice,  presenceByNum ! n)

    presenceByNum = listArray (bounds freqs) presenceList  where
        presence c | (c > 0) = Present | otherwise = Absent
        presenceList = [presence cnt | cnt <- elems freqs]

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = calcDP maxNum Chosen
        f _      _       = calcDP maxNum Removed

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit
default: all

all: time-hs run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary

run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
time-cpp: ./a.out 10pow5shuffled.in.txt
	cat -- 10pow5shuffled.in.txt | time ./a.out

run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary
time-hs: ./hs.exec 10pow5shuffled.in.txt
	cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000

10pow5shuffled.in.txt:
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt
	wc -l -- 10pow5shuffled.in.txt

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -Wall -Wextra -O3 -Werror $+
./hs.exec: my-copied.hs
	ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs
/10pow5shuffled.in.txt

--}

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
-- http://mivael.in.ua
--

import qualified Prelude as P
import Prelude (($), (.), (-), (+), (*),
                otherwise, Bool(True), Bool(False), error, const, undefined)
import System.IO (IO)
import qualified Data.List as L
import qualified Data.ByteString.Lazy.Builder as BB
import qualified Data.ByteString.Lazy.Char8 as BL8
import Data.ByteString.Lazy.Builder.ASCII (int64Dec)
import Data.Int (Int64)
import Data.Char (isSpace)
import Data.Maybe
import Data.Functor
import Data.Eq
import Data.Ord

import Data.Array (Ix, (!), listArray, accumArray, range, Array)

main :: IO ()
main = BL8.interact $ BL8.unlines . L.map (showResult . solveCase) . readCases
    where
      showResult = BB.toLazyByteString . int64Dec
      readCases = L.unfoldr readCase

type ANum = Int64  -- elements of a[]
type ASum = Int64  -- sum of ANum values
type Cnt = Int64  -- number of elements in a[]

type Case = [Int64]
type Result = ASum

readInt64 :: BL8.ByteString -> Maybe (Int64, BL8.ByteString)
readInt64 bs = conv <$> BL8.readInteger (BL8.dropWhile isSpace bs)  where
    conv (num, bsRest) = (P.fromIntegral num :: Int64, bsRest)

-- 'readN n f i s' is like 'f s' but reads n consequential elements
-- from s, not just one.
-- 'i s' == True iff s is an empty string.
-- 'readN 0 f i s' is Nothing if (i s == True),
-- otherwise, 'readN n f i s' is an error if (i s == True).
-- It is an error if it is impossible to read n elements form s.
readN :: P.Integral n =>
         n -> (s -> Maybe (m, s)) -> (s -> Bool) -> s -> Maybe ([m], s)
readN cnt readFunc nullFunc str = rn2 cnt str  where
    rn2 c s = rn c s (nullFunc s)
    rn 0 _ True  = Nothing
    rn 0 s False = Just ([], s)
    rn n s _     = Just (firstElem : otherElems, strRest2)  where
        (firstElem, strRest) = fromJust (readFunc s)
        (otherElems, strRest2) = unpack $ rn2 (n-1) strRest
        unpack Nothing    = ([], strRest)
        unpack (Just res) = res

readCase :: BL8.ByteString -> Maybe (Case, BL8.ByteString)
readCase bsWithSpaces
    | BL8.null bs = Nothing
    | otherwise = readN n readInt64 BL8.null bsRest
    where
      bs = BL8.dropWhile isSpace bsWithSpaces
      (n, bsRest) = fromJust (readInt64 bs)

solveCase :: Case -> Result
solveCase = solveFreqs . toFreqs

type Freqs = Array ANum Cnt
data FreqsAndMaxnum = FreqsMx Freqs ANum

-- Convert input data to a num-->frequencies mapping.
toFreqs :: [ANum] -> FreqsAndMaxnum
toFreqs listA = FreqsMx freqs maxA
    where
      maxA = L.maximum listA
      freqs = accumArray (const . (+1)) 0 (-1,maxA) [(num, undefined) | num <- listA]

-- Whether ANum is chosen.
data NumChoice = Chosen | Removed deriving (Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqsAndMaxnum -> ASum
solveFreqs (FreqsMx freqs maxA) = calcDP (maxA+1) Removed  where
    calcDP i numChoice = prevDP + thisSum  where
        (iprev, thisSum) = param numChoice  where
            param Removed = (i-1,  0)
            param Chosen  = (i-2,  (freqs ! i) * i)
        prevDP = r $ freqs ! iprev  where
            r 0 = get Removed
            r _ = max (get Removed) (get Chosen)
            get choicePrev = dpMemo ! (iprev, choicePrev)
    dpMemo = listArray memoBounds [dp n c
                                   | (n, c) <- range memoBounds]
      where
        memoBounds = ((-1, Chosen),
                      (maxA, Removed))
        dp (-1) _ = 0
        dp   0  _ = 0
        dp maxNum numChoice = calcDP maxNum numChoice

{-- Makefile --

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs time-cpp time-hs show-res default all submit
default: all

all: time-hs run-hs show-res submit

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary

run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
time-cpp: ./a.out 10pow5shuffled.in.txt
	cat -- 10pow5shuffled.in.txt | time ./a.out

run-hs: ./hs.exec gen.in.txt
	printf '1\n57' | ./hs.exec
	printf '1\n57\n' | ./hs.exec
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary
time-hs: ./hs.exec 10pow5shuffled.in.txt
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -p -K100000000
	#cat -- 10pow5shuffled.in.txt | time ./hs.exec +RTS -K16777216
	time ./hs.exec +RTS -K16777216 < 10pow5shuffled.in.txt
	#time ./hs.exec +RTS -p -K16777216 < 10pow5shuffled.in.txt

10pow5shuffled.in.txt:
	{ echo 100000;  printf '%s\n' {1..100000} | shuf; } > 10pow5shuffled.in.txt
	wc -l -- 10pow5shuffled.in.txt

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -D'MIVAEL_DEBUG' -Wall -Wextra -pedantic -Werror -std=c++11 -O3 $+
./hs.exec: my-copied.hs
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -O2 -o '$@' $+
	#ghc -prof -fprof-auto -rtsopts -Wall -Werror -o '$@' $+
	ghc -rtsopts -Wall -Werror -O2 -o '$@' $+

submit: temp-for-submit.hs
temp-for-submit.hs: my-copied.hs Makefile gener.py .gitignore
	cat -- my-copied.hs > '$@'
	printf '\n{-- %s --\n\n' Makefile >> '$@'
	cat -- Makefile >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' gener.py >> '$@'
	cat -- gener.py >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'
	printf '\n{-- %s --\n\n' .gitignore >> '$@'
	cat -- .gitignore >> '$@'
	printf '\n%s\n\n' '--}' >> '$@'

--}

{-- gener.py --

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 6
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

{-- .gitignore --

/gen.*.txt
/temp-for-submit.hs
/10pow5shuffled.in.txt

--}

import Data.List
import Control.Arrow
main=getContents>>=print.g.map read.tail.words
g=uncurry max.snd.foldl' f(0,(0,0)).map(head&&&genericLength).group.sort
 where f(a,(b,c))(d,e)|a+1<d=(d,(max(d*e+b)(max b c),max b c))|1>0=(d,(max(d*e+c)b,b))

import Data.List (foldl', genericLength, group, sort)
import Control.Arrow ((&&&))

main :: IO ()
main = getContents >>= print . solve . map read . tail . words

solve :: [Integer] -> Integer
solve = uncurry max . snd . foldl' f (0, (0, 0)) . map (head &&& genericLength) . group . sort
  where f (a, (b, c)) (d, e) | a + 1 < d = (d, (max (d * e + b) (max b c), max b c))
                             | otherwise = (d, (max (d * e + c) b, b))

import Data.List (foldl', genericLength, group, sort)
import Control.Arrow ((&&&))

main :: IO ()
main = getContents >>= print . solve . map read . tail . words

solve :: [Integer] -> Integer
solve = uncurry max . snd . foldl' f (0, (0, 0)) . map (head &&& genericLength) . group . sort
  where f (a, (b, c)) (d, e) | a + 2 < d = (d, (d * e + max b c, max b c))
                             | a + 1 < d = (d, (max (d * e + b) (max b c), max b c))
                             | otherwise = (d, (max (d * e + c) b, b))

import Data.Array
import Data.List
import Control.Arrow
main = do
  getLine
  ns <- fmap (map (head &&& genericLength) . group . sort . map read . words) getLine
  print $ solve ns
solve ns = go 0 ns where
  s = length ns
  go _ [] = 0
  go _ [(n,c)] = n*c
  go i ((n,c):(m,_):_)
    | m == n + 1 = maximum [
                       go' (i+1)
                     , n*c + go' (i+2)
                     , n*c + go' (i+3)
                   ]
    | otherwise = go' (i+1) + n*c
  go' = let a = listArray (0,s+2) $ zipWith go [0..] (tails ns) ++ [0,0]
        in \i -> a ! i

-- Vicfred
-- https://codeforces.com/problemset/problem/455/A

import Data.Int
import Data.Array

solve1 :: Array Int Int64 -> Int -> Int64
solve1 a = (r !)
    where r = listArray (0, 100000) (0 : a ! 1 : map f [2..100000])
          f i = max (r ! (i - 1)) (a ! i + r ! (i - 2))

(+^) :: Int64 -> Int -> Int64
a +^ b = a + fromIntegral b

solve :: [Int] -> Int64
solve a = solve1 cnt 100000
    where cnt = accumArray (+^) 0 (1, 100000) (zip a a)

main :: IO ()
main = do
    getLine
    nums <- fmap read . words <$> getLine :: IO [Int]
    print $ solve nums

import Control.Applicative
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.Maybe
import Data.Array

xx=100000

main= do
	getLine
	a<- map (fst.fromJust.C.readInteger). C.words <$> C.getLine::IO [Integer]
	let b= accumArray (+) 0 (1,xx) [(i,1)|i<-a]:: Array Integer Integer
	let c =array (0,xx) ((0,0):(1,(b!1)):[(i,max (c!(i-1)) ((c!(i-2))+i*(b!i)))|i<-[2..xx]]) :: Array Integer Integer
	print $ c!xx

import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Control.Arrow ((&&&))
import Data.List (group, sort)
import Data.Array

input :: IO [Int]
input = getLine >> fmap (map read . words) getLine

toAssocs :: [Int] -> [(Int, Integer)]
toAssocs = map (head &&& fromIntegral . length) . group . sort

solve :: [Int] -- List of numbers
      -> Integer   -- Max score
solve xs = m!100000
  where
    cs = Map.fromList . toAssocs $ xs
    count x = maybe 0 id $ Map.lookup x cs
    m = array (0, 100000) $
          [(0, 0), (1, count 1)] ++
          [(i, f i) | i <- [2..100000]]
    f n = max takeN ignoreN
      where takeN   = m!(n-1)
            ignoreN = m!(n-2) + (fromIntegral n * count n)

output :: Integer -> IO ()
output = putStrLn . show

main :: IO ()
main = output . solve =<< input

import Data.Int (Int64)
import Data.List (sort, group)

process :: [Int64] -> Int64
process = uncurry max . snd . foldr g (maxBound,(0,0)) . map f . group . sort
    where
        f xs = (head xs, sum xs)
        g (x,p) (y,(ay,aprev))
            | y-x == 1 = (x,(p+aprev,amax))
            | otherwise = (x,(p+amax,amax))
            where amax = max ay aprev

readInt :: String -> Int64
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    print $ process xs

import Data.List
import Data.IntMap.Lazy hiding (foldl)
import Control.Arrow
import Data.Int
import Data.ByteString.Builder
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe

solution :: IntMap Int64 -> Int64
solution mp = snd $ foldl recIncr (0, 0) [1..maxKey]
    where
        maxKey = fst $ findMax mp

        recIncr :: (Int64, Int64) -> Int -> (Int64, Int64)
        recIncr (res1, res2) ind3 =
            let res3 = max res2 (res1 + lkp ind3 * fromIntegral ind3) in (res2, res3)

        lkp :: Int -> Int64
        lkp n = findWithDefault 0 n mp

parseInput :: BS.ByteString -> IntMap Int64
parseInput = fromList  . fmap (head &&& genericLength) . group . sort
                . fmap (fst . fromJust . BS.readInt) . tail . BS.words

solve :: BS.ByteString -> BS.ByteString
solve = toLazyByteString . int64Dec . solution . parseInput

main :: IO ()
main = BS.interact solve

import Data.Int
import Data.ByteString.Builder
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe
import Data.Array.IArray

solution :: Array Int Int64 -> Int64
solution mp = snd $ foldl accumulator (0, 0) [1..upperBound]
    where
        upperBound = snd $ bounds mp

        accumulator :: (Int64, Int64) -> Int -> (Int64, Int64)
        accumulator (res1, res2) ind3 =
            let res3 = max res2 (res1 + (mp ! ind3) *  fromIntegral ind3)
            in (res2, res3)

parseInput :: BS.ByteString -> Array Int Int64
parseInput = hist (0, 100000) . fmap (fst . fromJust . BS.readInt) . tail . BS.words

hist :: (Ix a, Num b) => (a,a) -> [a] -> Array a b
hist bnds is = accumArray (+) 0 bnds [(i, 1) | i<-is, inRange bnds i]

solve :: BS.ByteString -> BS.ByteString
solve = toLazyByteString . int64Dec . solution . parseInput

main :: IO ()
main = BS.interact solve

import Data.List
import Data.IntMap.Lazy hiding (foldl)
import Control.Arrow
import Data.Int

solution :: IntMap Int64 -> Int64
solution mp = snd $ foldl recIncr (0, 0) [1..maxKey]
    where
        maxKey = fromIntegral $ fst $ findMax mp

        recIncr :: (Int64, Int64) -> Int64 -> (Int64, Int64)
        recIncr (res1, res2) ind3 =
            let res3 = max res2 (res1 + lkp ind3 * ind3) in (res2, res3)

        lkp :: Int64 -> Int64
        lkp n = fromIntegral $ findWithDefault 0 (fromIntegral n) mp

parseInput :: String -> IntMap Int64
parseInput = fromList . fmap (head &&& (fromIntegral.length)) . group . sort
                . fmap read . tail . words

solve :: String -> String
solve = show . solution . parseInput

main :: IO ()
main = interact solve

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.Array.Unboxed
import Data.List

main = putStr . evalState app . B.words =<< B.getContents

app = show `fmap` solve `fmap` (flip replicateM poi =<< poi)
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve xs = snd $ foldl' (\(!prev, !curr) (x, f) -> (curr, max curr $ prev + x * f)) (0, snd $ head freq) $ tail freq
  where
  freq = assocs (accumArray (+) 0 (0, maximum xs) $ zip xs (repeat 1) :: UArray Int Int)

import Data.List
import qualified Data.Map as Map

count l = sort $ map (\g -> (head g, length g)) $ group (sort l)

g :: Int -> Int -> Int -> Map.Map Int Int -> Int
g pprev prev i elems
  | i > (fst . Map.findMax) elems = max pprev prev
  | otherwise =
    let v = max prev (pprev + i * Map.findWithDefault 0 i elems)
    in g prev v (i+1) elems

f :: [Int] -> Int
f xs = g 0 0 0 (Map.fromList $ count xs)

main = interact $ show . f . (map read) . words . head . tail . lines

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
import Data.Array
-- import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
-- import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

-- getInts = fmap (map read . words) getLine
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  getLine
  as <- getInts

  let
    cs = accumArray (+) 0 (1, 10^5) $ zip as $ repeat 1

    r = listArray (0, 10^5) $ map f [0..10^5]
      where
        f 0 = 0
        f 1 = cs!1
        f i = max (r!(i-1)) (r!(i-2) + i*cs!i)

  print $ r!(10^5)

import Data.Array

main :: IO ()
main = do
  n <- readLn
  xs <- map read.words <$> getLine
  print $ solve n xs

solve :: Integer -> [Integer] -> Integer
solve n xs = res!n
  where
    arr = accumArray (+) 0 (1,100000) [(x,x)|x <- xs]
    res = listArray (0,n) $ 0:(arr!1):[max (arr!i + res!(i-2)) (res!(i-1))| i <- [2..n]]

import Data.Array

main :: IO ()
main = do
  n <- readLn
  xs <- map read.words <$> getLine
  print $ solve n xs

solve :: Integer -> [Integer] -> Integer
solve n xs = res!n
  where
    arr = accumArray (+) 0 (1,100000) [(x,x)|x <- xs] :: Array Integer Integer
    res = listArray (0,n) $ 0:(arr!1):[max (arr!i + res!(i-2)) (res!(i-1))| i <- [2..n]] :: Array Integer Integer

import Data.Array

main :: IO ()
main = do
  n <- readLn
  xs <- map read.words <$> getLine
  print $ solve n xs

solve :: Integer -> [Integer] -> Integer
solve n xs = res!n
  where
    arr = accumArray (+) 0 (1,100000) [(x,x)|x <- xs] :: Array Integer Integer
    res = listArray (0,100000) $ 0:(arr!1):[max (arr!i + res!(i-2)) (res!(i-1))| i <- [2..100000]] :: Array Integer Integer

import Control.Applicative
import Data.Array.IArray
import qualified Data.Foldable as F
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

main = do
    n <- readLn :: IO Int
    a <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine
    let s = accumArray (+) 0 (1, 10 ^ 5)  [(x, toInteger x) | x <- a] :: Array Int Integer
    let dp = array (0, n) ((0, 0) : (1, s ! 1) : [(i, max (dp ! (i - 1)) ((dp ! (i - 2) ) + s ! (i - 1))) | i <- [2 .. n]]) :: Array Int Integer
    putStrLn . show . F.foldl max 0 $ dp

import Control.Applicative
import Data.Array.IArray
import qualified Data.Foldable as F
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

main = do
    n <- readLn :: IO Int
    a <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine
    let s = accumArray (+) 0 (1, 10 ^ 5)  [(x, toInteger x) | x <- a] :: Array Int Integer
    let dp = array (0, n) ((0, 0) : (1, s ! 1) : [(i, max (dp ! (i - 1)) ((dp ! (i - 2) ) + s ! i)) | i <- [2 .. n]]) :: Array Int Integer
    putStrLn . show . F.foldl max 0 $ dp

import Data.List
import Data.Maybe
import Data.Char
import Data.Function
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.map read. words.head. tail.lines
solve :: [Int]->String
solve xs = show $ head $ slv1 $ foldr f [] $ sort xs
  where
  f a []  = [[a,1]]
  f a ([b1,b2]:xs)  = if a==b1 then ([b1,b2+1]:xs) else [a,1]:([b1,b2]:xs)
slv1 xss =foldr f1 [] xss where
  f1 [a1,a2] [] = [a2*a1,a2*a1]
  f1 [a1,a2] [sum1,prev]= if a1*a2-prev>0 then [a1*a2-prev+sum1, a2*a1] else [sum1,0]

import Data.List
import Data.Maybe
import Data.Char
import Data.Function
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.map read. words.head. tail.lines
solve :: [Int]->String
solve xs = show $ head $ slv1 $ foldr f [] $ sort xs
  where
  f a []  = [[a,1]]
  f a ([b1,b2]:xs)  = if a==b1 then ([b1,b2+1]:xs) else [a,1]:([b1,b2]:xs)
slv1 xss =foldr f1 [] xss where
  f1 [a1,a2] [] = [a2*a1,0,1,a1]
  f1 [a1,a2] [sum1,prev,l,a] | l==0 && a-a1<=1 = [sum1+a2*a1,sum1,1,a1]
                             | l==1 && a-a1<=1 = if a2*a1+prev>sum1 then [a2*a1+prev,sum1,1,a1] else [sum1,0,0,a1]
                             | a-a1>1       = [a2*a1+sum1,sum1,1,a1]

import Data.List
import Data.Maybe
import Data.Char
import Data.Function
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.map read. words.head. tail.lines
solve :: [Int]->String
solve xs = show $ head $ slv1 $ foldr f [] $ sort xs
  where
  f a []  = [[a,1]]
  f a ([b1,b2]:xs)  = if a==b1 then ([b1,b2+1]:xs) else [a,1]:([b1,b2]:xs)
slv1 xss =foldr f1 [] xss where
  f1 [a1,a2] [] = [a2*a1,0,1]
  f1 [a1,a2] [sum1,prev,l] | l==0 = [sum1+a2*a1,sum1,1]
                           | l==1 = if a2*a1+prev>sum1 then [a2*a1+prev,sum1,1] else [sum1,0,0]

import Data.List
import Data.Maybe
import Data.Char
import Data.Function
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.map read. words.head. tail.lines
solve :: [Int]->String
solve xs = show $ head.tail.slv1 $ foldr f [] $ sort xs
  where
  f a []  = [[a,1]]
  f a ([b1,b2]:xs)  = if a==b1 then ([b1,b2+1]:xs) else [a,1]:([b1,b2]:xs)
slv1 xss =foldr f1 [] xss where
  f1 [a1,a2] [] = [a1,a2*a1,0, 1]
  f1 [a1,a2] [prev,sum1,sum2,l] | prev-1==a1 && a2*a1 +sum2 >  sum1 && l==1 = [a1, a2*a1 +sum2, sum1, 1]
                                | prev-1==a1 && a2*a1 +sum2 <= sum1 && l==1 = [a1, sum1 ,a2*a1 +sum2, 0]
                                | l==0                                      = [a1, sum1+a2*a1, sum2,  1]
                                | otherwise                                 = [a1, sum1+a2*a1 ,0,1]

import Control.Monad
import Data.Array
import Data.Char
import Data.Functor
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = map (read . B.unpack) . B.words <$> B.getLine
getIntList :: IO [Int]
getIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

-- best result only selecting numbers <= i
solve1 :: Array Int Int -> Int -> Int64
solve1 a = (r !)
    where r = listArray (0, 100000) (0 : fromIntegral (a ! 1) : map f [2..100000])
          f i = max (r ! (i - 1)) (fromIntegral (a ! i) + r ! (i - 2))

solve :: [Int] -> Int64
solve a = solve1 cnt 100000
    where cnt = accumArray (+) 0 (1, 100000) (zip a a)

main :: IO ()
main = getLine >> getIntList >>= print . solve

import Control.Monad
import Data.Array
import Data.Char
import Data.Functor
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = map (read . B.unpack) . B.words <$> B.getLine
getIntList :: IO [Int]
getIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

-- best result only selecting numbers <= i
solve1 :: Array Int Int -> Int -> Int
solve1 a = (r!)
    where r = listArray (0,100000) (0 : a!1 : map f [2..100000])
          f i = max (r!(i - 1)) (a!i + r!(i - 2))

solve :: [Int] -> Int
solve a = solve1 cnt 100000
    where cnt = accumArray (+) 0 (1,100000) (zip a a)

main :: IO ()
main = getLine >> getIntList >>= print . solve

import Data.Array.MArray
import Data.Array.IO

type IntArray = IOArray Int Int

preProcess :: IO IntArray
preProcess = do
    count <- newArray (0, 100000) 0
    getLine
    a <- (getLine >>= (return . map read . words)) :: IO [Int]
    mapM_ (\x -> (readArray count x) >>= ((writeArray count x) . (+x))) a
    return count

solve :: [Int] -> Int
solve count = dp !! 100000
    where dp = 0 : (count!!1) : zipWith max (zipWith (+) dp (drop 2 count)) (tail dp)

main = do
    preProcess >>= getElems >>= (print . solve)

import Control.Applicative
import Control.Monad
import Data.List

main=do
     getLine
     q<-  map read <$> words <$>getLine ::IO [Int]
     let r= maximum $ map (\z->(length z,head z)) $ group $ sort q
     print r

import Control.Applicative
import Control.Monad
import Data.List

main=do
     getLine
     q<-  map read <$> words <$>getLine ::IO [Int]
     let r= maximum $ map (\z->(max (length z-1) 1)*(head z)) $ group $ sort q
     print r

import Control.Applicative
import Control.Monad
import Data.List
import Data.Array

process::[(Int,Int)]->Int
process q = dp!(100100)
   where qq = accumArray (+) 0 (1,100100) q
         dp =array (0,100100) ([(0,0),(1,qq!1)]
           ++ [(i,max (dp!(i-2)+qq!i) (dp!(i-1)))|i<-[2..100100]])

main=do
     getLine
     q<-  map (\z-> (head z,sum z)) <$> group <$> sort <$> map read <$> words <$>getLine ::IO [(Int,Int)]
     print $ process q

import Control.Applicative
import Control.Monad
import Data.List

main=do
     getLine
     q<-  map read <$> words <$>getLine ::IO [Int]
     let r= maximum $ map (\z->(length z,head z)) $ group $ sort q
     print $ snd r

import Control.Applicative
import Control.Monad
import Data.List
import Data.Array

process q = dp!(lq)
   where dp =array (0,lq) ([(0,0),(1,q!!0)]
           ++ [(i,max (dp!(i-2)+q!!(i-1)) (dp!(i-1)))|i<-[2..lq]])
         lq = length q

main=do
     getLine
     q<-  map sum <$> group <$> sort <$> map read <$> words <$>getLine ::IO [Int]
     print $ process q

import Control.Applicative
import Control.Monad
import Data.List

main=do
     getLine
     q<-  map read <$> words <$>getLine ::IO [Int]
     let r= maximum $ map (\z->(length z-1)*(head z)) $ group $ sort q
     print r

import Data.List

add :: (a -> a -> Bool) -> a -> [[a]] -> [[a]]
add eq x ((y:ys):others) = if eq x y then (x:y:ys):others else [x]:(y:ys):others
add eq x [] = [[x]]

adjacentGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
adjacentGroupBy eq xs = foldr (add eq) [] xs

evens :: [a] -> [a]
evens (x:xs) = x:(odds xs)
evens [] = []

odds :: [a] -> [a]
odds (_:xs) = evens xs
odds [] = []

group_score :: [(Int, Int)] -> Int
group_score groups =
    max (score $ evens groups) (score $ odds groups)
    where score = sum . map (\x -> fst x * snd x)

max_score :: [Int] -> Int
max_score nums =
    let
        pairs = map (\xs -> (head xs, length xs)) $ groupBy (==) $ sort nums
        groups = adjacentGroupBy (\x y -> (abs (fst x - fst y)) <= 1) pairs
    in
        sum $ map group_score groups

main = do
    getLine
    nums <- getLine
    print $ max_score $ map read $ words nums

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Data.List (sort, group)
import Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)
import Control.Arrow ((&&&))

-- import Debug.Trace (trace)
-- mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x

main :: IO ()
main = interact $ show . solveTC . map read . words
    where
      solveTC (n:listA) = solveFreqs . toFreqs n $ listA
      solveTC _ = error "Length and list are expected."

type ANum = Int  -- elements of a[]
type ASum = Int  -- sum of ANum values
type Cnt = Int  -- number of elements in a[]

type FreqArray = Array ANum Cnt

-- Convert input data to an array of frequencies.
toFreqs :: Cnt -> [ANum] -> FreqArray
toFreqs lenA listA
    | (length listA /= lenA) = error "Wrong length."
    | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA
    where
      freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList
          where
            maxA = getNum . head $ assocList
            getNum (num,_cnt) = num

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (Show, Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (Show, Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqArray -> ASum
solveFreqs freqsArray = maxDP maxA  where
    maxA = snd . bounds $ freqsArray
    maxDP i = (max
               (dpMemo ! (i, Chosen,  presenceByNum i))
               (dpMemo ! (i, Removed, presenceByNum i)))
    countByNum num
        | num > 0 = freqsArray ! num
        | otherwise = 0
    presenceByNum = toPresence . countByNum
    toPresence count | count > 0 = Present | otherwise = Absent

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = maxDP (maxNum-2) + (maxNum * countByNum maxNum)
        f _      _       = maxDP (maxNum-1)

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

--
-- Michael V. Antosha
-- 2017
-- Michael.Antosha@gmail.com
--
-- http://mivael.in.ua
--

import Data.List (sort, group)
import Data.Array (Array, accumArray, bounds, (!))
import Control.Arrow ((&&&))

main :: IO ()
main = interact $ show . solveTC . map read . words
    where
      solveTC (n:listA) = solveFreqs . toFreqs n $ listA
      solveTC _ = error "Length ans list are expected."

type ANum = Int  -- elements of a[]
type ASum = Int  -- sum of ANum's
type Cnt = Int  -- number of elements in a[]

type FreqArray = Array ANum Cnt

-- Input data to the array of frequencies.
toFreqs :: Cnt -> [ANum] -> FreqArray
toFreqs lenA listA
    | (length listA /= lenA) = error "Wrong length."
    | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA
    where
      freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList
          where
            maxA = getNum . head $ assocList
            getNum (num,_cnt) = num

data NumChoice = Chosen | Removed  -- whether ANum is chosen
data Presence = Present | Absent  -- whether ANum is present in a[]

-- Solve the array of frequencies.
solveFreqs :: FreqArray -> ASum
solveFreqs freqsArray = maxDP maxA  where
      maxA = snd . bounds $ freqsArray
      maxDP i = max (dp i Chosen) (dp i Removed)

      dp 0 _ = 0
      dp maxNum choice = f choice presence  where
          presence | cnt > 0 = Present | otherwise = Absent
          nprev = maxNum - 1
          cnt = freqsArray ! maxNum

          f Removed Present = dp nprev Chosen
          f Removed Absent  = maxDP nprev
          f Chosen  Present = maxNum * cnt + dp nprev Removed
          f Chosen  Absent  = 0

--
-- Michael V. Antosha
-- 2017
-- m.antosha@samsung.com
--

import Data.List (sort, group)
import Data.Array (Array, accumArray, bounds, (!), listArray, range, Ix)
import Control.Arrow ((&&&))

-- import Debug.Trace (trace)
-- mytrace :: Show a => String -> a -> a
-- mytrace s x = trace ("trace: " ++ s ++ ": " ++ show x ++ ".") x

main :: IO ()
main = interact $ concat . map (++ "\n") . map show . solveMany . map read . words
    where
      solveMany [] = []
      solveMany (n:rest) = (solveTC $ n : take n rest) : (solveMany $ drop n rest)
      solveTC (n:listA) = solveFreqs . toFreqs n $ listA
      solveTC _ = error "Length and list are expected."

type ANum = Int  -- elements of a[]
type ASum = Int  -- sum of ANum values
type Cnt = Int  -- number of elements in a[]

type FreqArray = Array ANum Cnt

-- Convert input data to an array of frequencies.
toFreqs :: Cnt -> [ANum] -> FreqArray
toFreqs lenA listA
    | (length listA /= lenA) = error "Wrong length."
    | otherwise = freqsAsArray . map (head &&& length) . group . reverse . sort $ listA
    where
      freqsAsArray assocList = accumArray (+) 0 (1, maxA) assocList
          where
            maxA = getNum . head $ assocList
            getNum (num,_cnt) = num

data NumChoice = Chosen | Removed  -- whether ANum is chosen
                deriving (Show, Eq, Ord, Ix)
data Presence = Present | Absent  -- whether ANum is present in a[]
                deriving (Show, Eq, Ord, Ix)

-- Solve, given an array of frequencies.
solveFreqs :: FreqArray -> ASum
solveFreqs freqsArray = maxDP maxA  where
    maxA = snd . bounds $ freqsArray
    maxDP i = (max
               (dpMemo ! (i, Chosen,  presenceByNum i))
               (dpMemo ! (i, Removed, presenceByNum i)))
    countByNum num
        | num > 0 = freqsArray ! num
        | otherwise = 0
    presenceByNum = toPresence . countByNum
    toPresence count | count > 0 = Present | otherwise = Absent

    dp (-1) _ _ = 0
    dp   0  _ _ = 0
    dp maxNum numChoice numPresence = f numChoice numPresence  where
        f Chosen Present = maxDP (maxNum-2) + (maxNum * countByNum maxNum)
        f _      _       = maxDP (maxNum-1)

    memoBounds = ((-1, Chosen, Present),
                  (maxA, Removed, Absent))
    dpMemo = listArray memoBounds [dp n c p
                                   | (n, c, p) <- range memoBounds]

{-- Makefile

export SHELL = /bin/bash -o pipefail

.PHONY: run-cpp run-hs show-res default all
default: run-cpp
all: run-cpp run-hs show-res

show-res: gen.res.txt
	cat -- '$+' | sha1sum --binary
run-cpp: ./a.out gen.in.txt
	cat -- gen.in.txt | ./a.out | sha1sum --binary
run-hs: ./hs.exec gen.in.txt
	cat -- gen.in.txt | ./hs.exec | sha1sum --binary

gen.res.txt: gen.stamp.txt
gen.in.txt: gen.stamp.txt

gen.stamp.txt: gener.py
	python3 gener.py
	touch gen.stamp.txt
	ls -ld -- gen.*.txt

./a.out: *.cpp
	g++ -Wall -Wextra -std=c++0x -pedantic -Werror $+
./hs.exec: *.hs
	ghc -Wall -Werror -o '$@' $+

--}

{-- gener.py

import itertools
import collections

def main():
    maxN = 5
    print("maxN = {!r}." . format(maxN))
    maxA = 9
    print("maxA = {!r}." . format(maxA))
    writeCase = CaseWriter(inputsFilename='gen.in.txt', resultsFilename='gen.res.txt')
    for n in [i+1 for i in range(maxN)]:
        print("n = {!r}." . format(n))
        for arrA in itertools.product([i+1 for i in range(maxA)], repeat=n):
            # print("arrA = {!r}." . format(arrA))
            writeCase(inputArr=arrA, result=solve(arrA))

def solve(arrA):
    max_points = 0
    for order in itertools.permutations(range(len(arrA))):
        num2inds = collections.defaultdict(set)
        for ind, num in enumerate(arrA):
            num2inds[num].add(ind)
        points = 0
        for ind in order:
            # print("order = {!r} (len={!r}), ind = {!r}." . format(order, len(order), ind))
            num = arrA[ind]
            if len(num2inds[num]) == 0:
                continue
            points += num
            num2inds[num].remove(ind)
            num2inds[num-1].clear()
            num2inds[num+1].clear()
        max_points = max(points, max_points)
    return max_points

class CaseWriter:
    def __init__(self, inputsFilename, resultsFilename):
        self.inputs = open(inputsFilename, mode='w')
        self.results = open(resultsFilename, mode='w')
    def __call__(self, inputArr, result):
        print("{n!r}\n{a}" . format(n=len(inputArr), a=' '.join([str(ai) for ai in inputArr])), file=self.inputs)
        print("{!r}" . format(result), file=self.results)
        self.inputs.flush()
        self.results.flush()

main()

--}

import Data.List

main = do
    getLine
    nums <- getLine
    print $ max_score $ map read $ words nums

add :: (a -> a -> Bool) -> a -> [[a]] -> [[a]]
add eq x ((y:ys):others) = if eq x y then (x:y:ys):others else [x]:(y:ys):others
add eq x [] = [[x]]

adjacentGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
adjacentGroupBy eq xs = foldr (add eq) [] xs

max_first :: [Int] -> Int
max_first (x:y:_) = max x y
max_first (x:_) = x
max_first [] = 0

safe_tail :: [a] -> [a]
safe_tail (_:xs) = xs
safe_tail [] = []

dp_step :: [Int] -> (Int, Int) -> [Int]
dp_step acc x = ((fst x * snd x) + (max_first $ safe_tail acc)):acc

group_score :: [(Int, Int)] -> Int
group_score group =
    max_first dp
    where dp = foldl dp_step [] group

max_score :: [Int] -> Int
max_score nums =
    let
        pairs = map (\xs -> (head xs, length xs)) $ groupBy (==) $ sort nums
        groups = adjacentGroupBy (\x y -> (abs (fst x - fst y)) <= 1) pairs
    in
        sum $ map group_score groups

main :: IO ()
main = getContents >>= print . solve . map read . words

solve :: [Integer] -> Integer
solve (_:as) = max (sum (filter even as)) (sum (filter odd as))
solve _ = undefined

import Data.List (foldl', group, sort)
import Control.Arrow ((&&&))

main :: IO ()
main = getContents >>= print . solve . map read . tail . words

solve :: [Int] -> Int
solve = uncurry max . snd . foldl' f (0, (0, 0)) . map (head &&& length) . group . sort
  where f (a, (b, c)) (d, e) | a + 2 < d = (d, (d * e + max b c, max b c))
                             | a + 1 < d = (d, (max (d * e + b) (max b c), max b c))
                             | otherwise = (d, (max (d * e + c) b, b))

import Data.Array
import Data.List
import Control.Arrow
main = do
  getLine
  ns <- fmap (map (head &&& length) . group . sort . map read . words) getLine
  print $ solve ns
solve ns = go 0 ns where
  s = length ns
  go _ [] = 0
  go _ [(n,c)] = n*c
  go i ((n,c):(m,_):_)
    | m == n + 1 = maximum [
                       go' (i+1)
                     , n*c + go' (i+2)
                     , n*c + go' (i+3)
                   ]
    | otherwise = go' (i+1) + n*c
  go' = let a = listArray (0,s+2) $ zipWith go [0..] (tails ns) ++ [0,0]
        in \i -> a ! i

import Data.Array
import Data.List
import Control.Arrow
main = do
  getLine
  ns <- fmap (map (head &&& length) . group . reverse . sort . map read . words) getLine
  print $ solve ns
solve ns = go 0 ns where
  go _ [] = 0
  go _ [(n,c)] = n*c
  go i ((n,c):es@((m,d):es')) = max (go' (i+1) es) (n*c + go' (i+2) es')
  go' = let a = listArray (0,length ns) $ zipWith go [0..] (tails ns)
        in \i j -> a ! i

import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Control.Arrow ((&&&))
import Data.List (group, sort)
import Data.Array

input :: IO [Int]
input = getLine >> fmap (map read . words) getLine

toAssocs :: [Int] -> [(Int, Int)]
toAssocs = map (head &&& length) . group . sort

solve :: [Int] -- List of numbers
      -> Int   -- Max score
solve xs = m!100000
  where
    cs = Map.fromList . toAssocs $ xs
    count x = maybe 0 id $ Map.lookup x cs
    m = array (0, 100000) $
          [(0, 0), (1, count 1)] ++
          [(i, f i) | i <- [2..100000]]
    f n = max takeN ignoreN
      where takeN   = m!(n-1)
            ignoreN = m!(n-2) + (n*count n)

output :: Int -> IO ()
output = putStrLn . show

main :: IO ()
main = output . solve =<< input

import Data.Int (Int64)
import Data.List (sort, group)

process :: [Int64] -> Int64
process = maximum . snd . foldr g (maxBound,[0]) . map f . group . sort
    where
        f xs = (head xs, sum xs)
        g (x,p) (y,s@(a:as))
            | y-x == 1 = case as of
                            [] -> (x,[p,a])
                            (a':_) -> (x,[p+a',max a a'])
            | otherwise = (x,[p+maximum s])

readInt :: String -> Int64
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    print $ process xs

import Data.Int (Int64)
import Data.List (sort, group)

process :: [Int64] -> Int64
process = maximum . snd . foldr g (maxBound,[0]) . map f . group . sort
    where
        f xs = (head xs, sum xs)
        g (x,p) (y,s@(a:as))
            | y-x == 1 = case as of
                            [] -> (x,[p,a])
                            (a':_) -> (x,[p+a',a])
            | otherwise = (x,[p+maximum s])

readInt :: String -> Int64
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    print $ process xs