Sort the coins by increasing , and let be the weight of the -th coin in this order.
Two unflipped coins are always compatible as neighbors, whereas two flipped coins are never compatible. If exactly one of two neighboring coins is flipped, the condition holds precisely when the flipped coin has the larger .
Let be the number of flipped coins among the first coins in sorted order. Every flipped coin in such a prefix needs two neighboring, unflipped coins with smaller . Unless the prefix contains the entire circular arrangement, the induced paths must therefore contain at least one more unflipped coin than flipped coins. Consequently every feasible selection satisfies
These inequalities are also sufficient. List the unflipped coins as and the flipped coins as , each in increasing order of . If , arrange them as . If , arrange in a circle. The prefix inequalities ensure that every flipped coin has strictly larger than each adjacent unflipped coin.
It remains to maximize the sum of weights subject to these nested prefix-cardinality limits. Process the coins in increasing order of , inserting each weight into a min-heap. Whenever the heap size exceeds the limit for the current prefix, remove the smallest weight. The retained set is a maximum-weight feasible choice under all processed prefix limits. The final heap sum is the answer.
Sorting and heap operations take time and space.
Solution written by GPT6