To solve this problem, we need to determine the minimal number of elements to remove from a sequence so that the remaining sequence forms a zigzag pattern. A zigzag sequence alternates between increasing and decreasing consecutive elements, with no two consecutive elements being equal.
Approach
The key insight is to find the length of the longest zigzag subsequence. The minimal number of elements to remove is then the total length of the sequence minus the length of this longest zigzag subsequence.
We can efficiently compute the longest zigzag subsequence using dynamic programming with two variables:
up: The length of the longest zigzag subsequence ending at the current position with an upward trend (current element > previous element).down: The length of the longest zigzag subsequence ending at the current position with a downward trend (current element < previous element).
Transitions:
- If the current element is greater than the previous element, update
uptodown + 1(since we switch from a downward trend to an upward trend). - If the current element is less than the previous element, update
downtoup + 1(since we switch from an upward trend to a downward trend). - If the current element equals the previous element, no update is needed as consecutive equal elements are not allowed in a zigzag sequence.
Solution Code
n = int(input())
a = list(map(int, input().split()))
if n <= 1:
print(0)
else:
up = 1
down = 1
for i in range(1, n):
if a[i] > a[i-1]:
up = down + 1
elif a[i] < a[i-1]:
down = up + 1
longest = max(up, down)
print(n - longest)
Explanation
- Initialization: For a sequence of length 1, both
upanddownstart at 1 (since a single element is a valid zigzag sequence). - Iterate through the sequence: For each element, update
upordownbased on the comparn with the previous element. - Compute the result: The length of the longest zigzag subsequence is the maximum of
upanddown. The minimal number of elements to remove is the total length minus this value.
This approach runs in O(n) time complexity, which is optimal for the given problem constraints. It efficiently computes the desired result with minimal space usage (O(1) additional space).
Example:
- For the sequence [1,7,4,9,2,5], the longest zigzag subsequence length is 6 (all elements form a valid zigzag), so the minimal removal is 0.
- For the sequence [1,2,3,4,5], the longest zigzag subsequence length is 2, so the minimal removal is 5-2=3.
This solution handles all edge cases and provides the correct result for any valid input.


作者声明:本文包含人工智能生成内容。