For Christmas, Firebat received a new Hearthstone (a card game) expansion! In this game there is a deck of cards. Unfortunately for him, this expansion only contained draw cards. Each card has a mana cost and draw cards from the top of the deck. Still the optimist, Firebat created a deck out of only these draw cards. We all know Firebat is the ultimate hearthstone player, and thus, knows exactly the order of the cards in his deck, does not have a hand limit and can use more than 10 mana. Nevertheless, he would like to maximize value. He starts off the game with only the first card of his deck in his hand (it's only fair for his opponent). Help him by determining the minimum mana he needs to spend in order to draw his entire deck (and possible overdraw).
It will always be possible to draw all cards. Once Firebat plays a card, he cannot play it again.
First line: , the number of cards in his deck.
Next lines: the and values of the card of Firebat's deck (from top to bottom). .
A single integer, the minimum mana he must spend to draw his entire deck.
8 20 3 5 0 13 3 9 3 18 2 4 1 17 1 8 0
For the minimal cost, Firebat should play the first card, drawing the next three. He should then play the fourth card and then the sixth card, emptying the deck. This gives a total of mana.