Given an array of integers, find the length of the longest zigzag subsequence. A sequence is called a zigzag sequence if the differences between successive numbers strictly alternate between positive and negative. In other words, the elements of the subsequence alternate between increasing and decreasing order.
A sequence with fewer than two elements is trivially a zigzag subsequence.
A zigzag sequence alternates as follows:
x₁ < x₂ > x₃ < x₄ > x₅ < ...
That is, each element is alternately greater and less than its neighbors.
The main idea is to use dynamic programming to keep track of the longest zigzag subsequence ending at each index, considering both possible directions (up and down). For each element, we check all previous elements to see if we can extend a zigzag subsequence by increasing or decreasing.
classSolution {
publicintlongestZigzag(int[] arr) {
int n = arr.length;
if (n == 0) return 0;
int[] up =newint[n], down =newint[n];
Arrays.fill(up, 1); Arrays.fill(down, 1);
int ans = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (arr[i]> arr[j]) up[i]= Math.max(up[i], down[j]+ 1);
elseif (arr[i]< arr[j]) down[i]= Math.max(down[i], up[j]+ 1);
}
ans = Math.max(ans, Math.max(up[i], down[i]));
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
deflongest_zigzag(self, arr: list[int]) -> int:
n = len(arr)
if n ==0:
return0 up = [1] * n
down = [1] * n
ans =1for i in range(1, n):
for j in range(i):
if arr[i] > arr[j]:
up[i] = max(up[i], down[j] +1)
elif arr[i] < arr[j]:
down[i] = max(down[i], up[j] +1)
ans = max(ans, up[i], down[i])
return ans