Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

Array b = [1, 11, 2, 10, 4, 5, 2, 1]. Find the length of its longest bitonic subsequence: a subsequence that strictly increases and then strictly decreases (either part may be empty).

Array b = [1, 11, 2, 10, 4, 5, 2, 1]. Find the length of its longest bitonic subsequence: a subsequence that strictly increases and then strictly decreases (either part may be empty).
b=[1,11,2,10,4,5,2,1]
n=len(b)
L=[1]*n; D=[1]*n
for i in range(n):
    for j in range(i):
        if b[j]<b[i]: L[i]=max(L[i],L[j]+1)
for i in range(n-1,-1,-1):
    for j in range(i+1,n):
        if b[j]<b[i]: D[i]=max(D[i],D[j]+1)
print(max(L[i]+D[i]-1 for i in range(n)))
What is printed?
  1. A. 7
  2. B. 5
  3. C. 4
  4. D. 6

Correct answer: D. 6

L (increasing ending at i) and D (decreasing from i) peak at 10: 1, 2, 10 then 10, 5, 2, 1, so 3 + 4 − 1 = 6. The plain LIS is 4 (1, 2, 4, 5), the longest decreasing is 5 (11, 10, 5, 2, 1), and forgetting the − 1 for the shared peak gives 7.

More Coding Interview Problems questions

Exams that ask this topic