Removing wasted siege attacks
A siege attack targeting either endpoint decreases total health by at most , or at most when . Attacks in tank mode can reproduce the same decreases for a cost of at most . Therefore, an optimal solution exists that never targets an endpoint in siege mode.
A siege attack decreases the total health by at most . If any damage is lost because health is clipped at , its actual total decrease is at most . Replace that attack with attacks in tank mode producing exactly the same decreases. This reaches the same state for a cost of at most . Thus, an optimal solution exists in which every siege attack deals its full damage.
Maximizing the number of siege attacks
Let be the number of siege attacks targeting position . By the observation above, omit endpoint attacks and set . The following condition must hold at each position:
Conversely, if these conditions hold, we can perform the siege attacks in any order without wasting damage, then remove the remaining health with attacks in tank mode. If , the siege attacks remove total health , and the total cost is
It remains to maximize the sum of nonnegative integer values satisfying the conditions.
Dynamic programming
Let and . Every lies between and .
Immediately before processing position , let be the maximum sum of the chosen values , assuming that all conditions before position hold and , . Impossible states have value negative infinity. Initially, and all other states are impossible.
Choose . The current condition is , giving the transition
Only is allowed when . For each fixed , compute prefix maxima along to evaluate each transition in time. After processing position , is the maximum number of siege attacks.
The transitions enumerate every possible next count and check exactly the condition at the current position. Induction therefore proves that the DP preserves every feasible placement and its maximum count. The answer is .
The time complexity is and the space complexity is . Since , we have . Using also covers an all-zero input.
Subtasks
Solution written by GPT6