A carousel holds n token stacks arranged in a circle, each with a positive integer size. Because they sit in a ring, stack i is adjacent to stack i+1, and the last stack is also adjacent to the first. You combine them into a single stack by repeatedly merging two currently-adjacent stacks (adjacency is on the ring, so a wrap-around merge of the current first and last stacks is allowed) into one stack whose size is their sum. Each merge costs the size of the newly formed stack.
Report the minimum total cost to reduce the ring to a single stack.
Line 1: an integer n, the number of stacks.
Line 2: n space-separated positive integers, the stack sizes in clockwise order.
A single integer: the minimum total merging cost (0 if there is only one stack).
Example 1
Input
3 1 2 3
Expected
9
Explanation
Merging the 1 and 2 (cost 3) then the two size-3 stacks (cost 6) totals 9, which is optimal for this ring.
Example 2
Input
1 5
Expected
0
Explanation
There is only one stack, so no merges are needed: the cost is 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →