Cards
InterviewTime limit1sMemory limit32 MB
Two cards are compared at a time with the smaller pocketed, so find the largest possible sum of pocketed numbers for the given row.
- Level
Easy1 of 10
- Topics
- Array
- Solved
- No attempts yet
Problem
Seunghyun has cards, each with a front and a back. The front of each card holds one integer between and , and no two cards hold the same number. The back of each card has a picture of an animal, and no two cards have the same picture.

These are cards that could appear. The left picture is the front and the right picture is the back.
Seunghyun lays the cards on the floor in a row with the backs facing up and numbers them through in order. Let be the number on the front of card . Seunghyun repeats the following until exactly one card is left on the floor.
- He picks any two different cards he likes and turns them over so the fronts face up.
- He puts the card with the smaller number into his pocket and lays the card with the larger number back on the floor with the back facing up.
- If two or more cards are left on the floor, he goes back to step 1. If exactly one card is left, he takes every card out of his pocket and adds up the numbers on their fronts.
The animal pictures differ, so Seunghyun can tell the cards apart and can turn over exactly the two cards he wants every time. He likes big numbers, so he wants the final sum in his pocket to be as large as possible. Find that maximum sum.
Input
The first line holds a natural number , the number of cards. ()
The second line holds in order, separated by spaces. Each is an integer between and , and they are all different.
Output
Print the largest possible sum on the first line.
Hint
In the first example only one play is possible. Seunghyun turns over the card with and the card with , and after the card with goes into his pocket only one card is left on the floor, so the answer is .
In the second example three plays are possible.
- He turns over the cards with and , then the cards with and , so the sum is .
- He turns over the cards with and , then the cards with and , so the sum is .
- He turns over the cards with and , then the cards with and , so the sum is .
The answer is therefore .