Editorial
1. Representing a strategy as an order
If the imp does not cast a spell after a purchase, the game ends immediately. Therefore, the only continuation branch is that the just-bought item is destroyed. A strategy can consequently be represented by an order of distinct boxes.
Fix a positive target profit . Since the imp may destroy the first bought items, guaranteeing an obtained item requires planning boxes. For an order , if the first surviving item is , the required condition is
for every .
Profit is always available by leaving immediately.
2. Scheduling reduction
For a fixed , create one job for each box with processing time and deadline . The condition above asks for at least jobs that can all finish by their deadlines.
3. Maximum number of on-time jobs
Process jobs in nondecreasing deadline order. Insert each processing time into a max-heap and add it to the current total. If the total exceeds the current deadline, remove the largest processing time.
After every prefix, the heap contains a maximum-cardinality feasible subset, and among such subsets it has minimum total processing time. Removing the longest selected job is exactly the exchange that preserves this invariant.
The target is feasible if and only if the final heap size is at least .
Because deadlines are , their relative order is the same as the order of for every , so the items need to be sorted only once.
4. Binary search
Feasibility is monotone in . The answer lies between and , so binary-search this range.
A feasibility check costs . The total time complexity is
with memory.
Solution written by GPT5.6