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?- A. 5
- B. 6
- C. 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
- Problem: Two piles of stones (values [1, 6, 11, 5]) are to be divided into two groups whose sums differ as little as possible. What is the…
- Problem: You have 2 eggs and a building with 10 floors. What is the minimum number of drops needed in the worst case to find the highest…
- Problem: How many distinct ways can the string 'leetcode' be segmented into words from the dictionary {'leet', 'code', 'leetcode', 'lee'…
- Problem: Count the connected components of the undirected graph on 6 vertices with edges (0,1), (1,2), (3,4), (5,5) using DFS. Run the…
- Problem: Check whether the directed graph with edges 0->1, 1->2, 2->0, 2->3 contains a cycle using Kahn's algorithm (count the nodes that…
- Problem: Find the minimum cost to reach node 3 from node 0 using at most 2 edges in the directed graph with edges (0,1,5), (1,3,5)…