import Foundation

_ = readLine()
let friendlinessList = readLine()!
    .split(separator: " ")
    .compactMap { Int($0) }
    .sorted(by: >)

var circle = [(Int, Int, Int)]()
var comfortableness = [Int]()
var preds = [Int]()

for friendliness in friendlinessList {
    if circle.isEmpty {
        circle = [(friendliness, 0, friendliness)]
    } else if circle.count == 1 {
        let first = circle[0]
        circle = [
            (first.0, first.1, friendliness),
            (friendliness, first.1, friendliness),
        ]
    } else {
        let (index, max) = preds.lazy
            .enumerated()
            .max { $0.1 < $1.1 }!
        let old = circle[index]
        circle[index] = (old.0, old.1, friendliness)
        circle.insert((friendliness, max, friendliness), at: index)
    }
}

print(comfortableness.reduce(0, +))
