Suppose the element initially at position is the one that remains. Exactly elements to its left and elements to its right are deleted. Its final value is therefore
regardless of the deletion order.
Evaluate this expression at every position and take the maximum. Each expression can be evaluated as its element is read, keeping only the largest value seen so far. The time complexity for one case is and the auxiliary space complexity is .
Proof
While one element is kept until the end, its relative order with respect to every other element never changes. Deleting an element that was initially to its left decreases its value by , and deleting an element that was initially to its right increases its value by . Every other element is deleted exactly once, so the element initially at position always finishes with value .
For subtask , exhaustive search can try every choice of an element to delete from the current sequence and examine all possible final values. Modify the sequence in place, and restore it after each recursive call. This takes time and space for the sequence and recursion stack.
For subtask , choose each candidate for the final element in turn and add the contribution of deleting every other element individually. This takes time and space to store the sequence.
For every deletion order, the final element came from some position in the initial sequence. Its final value therefore cannot exceed the maximum of these expressions. Conversely, choose a position attaining that maximum and delete all other elements. This achieves that value, so the maximum of the expressions is exactly the answer.
For subtask , the condition means that decreases by at least when moving one position to the right. Keeping the first element is therefore optimal, and the answer is . Including the time to read the input, this takes time and auxiliary space.
Solution written by GPT6