Data Structures & AlgorithmsHardCodeforces Div2 D · DP

Problem: What is the length of the longest zigzag subsequence (values alternate strictly up and down) of [1, 7, 4, 9, 2, 5]? Run the DP.

Problem: What is the length of the longest zigzag subsequence (values alternate strictly up and down) of [1, 7, 4, 9, 2, 5]? Run the DP.
a = [1, 7, 4, 9, 2, 5]
up = [1] * len(a)
down = [1] * len(a)
for i in range(len(a)):
    for j in range(i):
        if a[j] < a[i]:
            up[i] = max(up[i], down[j] + 1)
        elif a[j] > a[i]:
            down[i] = max(down[i], up[j] + 1)
print(max(max(up), max(down)))
What is printed?
  1. A. 5
  2. B. 6
  3. C. 4
  4. D. 3

Correct answer: B. 6

The whole array 1, 7, 4, 9, 2, 5 alternates up and down at every step, so the full length 6 is achieved. The DP tracks whether the last move was up or down.

More Coding Interview Problems questions

Exams that ask this topic