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?- A. 7
- B. 5
- C. 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
- Count the 4-element subsets of {1, 2, ..., 12} whose sum is divisible by 5. Count by brute force over combinations. python from itertools…
- Find the smallest positive integer x such that x ≡ 2 (mod 3), x ≡ 3 (mod 5) and x ≡ 2 (mod 7). Solve by brute-force search. python…
- How many trailing zeros does 100! have in base 10? Use Legendre's formula with powers of 5, counted by running the loop over p = 5, 25…
- The string s = "abcbdab" needs characters deleted to become a palindrome. What is the minimum number of deletions? Use n minus the longest…
- A 4×4 grid has rows "..#.", ".##.", "##.#", "#...". Entering a cell costs 1 if it is '#' and 0 otherwise, and you may move in four…
- Array c = [1, 2, 3, 0, 3, 3, 0, 6]. In how many ways can it be split into three non-empty contiguous parts whose sums are all equal? Run…