Consider checking whether the answer can be at most .
Let the positions whose original values are kept be . If two consecutive kept positions are , it is necessary that
This condition is also sufficient. When the difference of the two endpoint values is at most , the changed positions between them can be filled with integers so that every step changes by at most . Changed prefixes and suffixes can always be filled as well.
Therefore, it is enough to determine whether at least original values can be kept.
Subtask 4:
Let be the maximum number of original values we can retain when position is the last retained position. By directly checking which earlier positions can be retained together with , we obtain
If no satisfies the condition, take the maximum to be .
Compute the states in the order and check whether . One feasibility check takes time. Using it in binary search gives time and space.
For each position , define
For , the condition above is equivalent to
Sort the points by decreasing , breaking ties by increasing . Let be the length of the longest nondecreasing subsequence of the values in this order. Then is exactly the maximum number of original values that can be kept.
For , since , any two points satisfying the two coordinate inequalities are also ordered by their original indices. For , we have , and a nondecreasing subsequence after decreasing- sorting can contain several points together only when their values are equal, which is also valid.
Thus is feasible exactly when . The longest nondecreasing subsequence can be computed in using upper_bound.
Feasibility is monotone in , so binary-search from to the maximum adjacent difference of the original sequence. The total time complexity is , where , and the memory complexity is .
Solution written by GPT6