Card Fusion Event
Time limit1sMemory limit512 MB
Merge adjacent cards until one remains, where a merge pays the sum of both levels and keeps only the left card's level; maximize total gold.
- Level
Medium6 of 10
- Topics
- Intervals, Dynamic programming
- Solved
- No attempts yet
Problem
Yeonggwan joined the card fusion event of a mobile board game.
The event puts cards in a row in a fixed order, and each card carries one level.
You may append card B to card A to merge them into a single card. The conditions are as follows.
- The two cards must be next to each other in the row.
- The level of the merged card equals the level of A. The level of the appended card B is gone.
- The merged card stays where the two cards were and counts as one card in later merges.
Each merge pays gold equal to the sum of the levels of the two cards right before they are merged.
Merging continues until one card is left, so exactly merges happen. Find the largest total gold Yeonggwan can receive.
Take three cards with levels 40, 30, 30. Appending to leaves a card of level 30 and pays 60 gold. Appending that card to leaves a card of level 40 and pays 70 gold, for a total of 130. In the other order, appending to leaves a card of level 40 and pays 70 gold, and appending to that card pays 70 gold again, for a total of 140.
Input
The first line contains the number of cards ().
The second line contains the levels of the cards, in the order they lie in the row ().
Output
Print the largest total gold on one line. If , no merge happens, so print 0.