We can set up a scheme, the consumption of magic looks like this: starting from 1 to choose a continuous segment of smaller magic, and then choose several scattered larger magic.
So we need to enumerate. The first magic that is not selected, and the continuous smaller magic before it, all need to be selected in this enumeration. As for the number of scattered larger magic options selected later, dp count (knapsack count).
Then we take an example to illustrate:
51436218
After sorting:
51412368
When we set 8 to be the first smaller magic that is not selected, the larger magic after 8 will be counted by dp.
When we set 6 to be the first smaller magic that is not selected, the larger magic after 6 is counted once by dp.
When we set 3 to be the first smaller magic that is not selected, the larger magic after 3 is counted once by dp.