Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional
Array a = [1, 3, 2, 3, 1, 4, 5, 2]. Subsequences are chosen by index (positions may repeat values). Count the strictly increasing subsequences whose length equals the longest strictly increasing subsequence length.
Array a = [1, 3, 2, 3, 1, 4, 5, 2]. Subsequences are chosen by index (positions may repeat values). Count the strictly increasing subsequences whose length equals the longest strictly increasing subsequence length.
a=[1,3,2,3,1,4,5,2]
n=len(a); L=[1]*n; C=[1]*n
for i in range(n):
for j in range(i):
if a[j]<a[i]:
if L[j]+1>L[i]: L[i]=L[j]+1; C[i]=C[j]
elif L[j]+1==L[i]: C[i]+=C[j]
m=max(L)
print(sum(C[i] for i in range(n) if L[i]==m))What is printed?- A. 1
- B. 2
- C. 5
- D. 20
Correct answer: A. 1
Track for each index the length and the number of ways to reach it; equal-length predecessors add their counts. Allowing equal values merges in extra subsequences, printing the length instead of the count is a plain misreading, and letting a longer predecessor add its ways instead of replacing them overcounts.
More Coding Interview Problems questions
- Two strings are "intention" and "execution". Compute the minimum cost to turn the first into the second, where insertion and deletion cost…
- A staircase is climbed with steps of size 1, 3 or 4 (order of steps matters). How many distinct ordered sequences of steps reach exactly…
- Forty-one people stand in a circle numbered 1 to 41. Starting from person 1, every third person is removed, repeatedly, counting continues…
- Compute the sum of the prefix-function (KMP failure) array of the string "abacabab", where pi[i] is the length of the longest proper…
- A directed weighted graph has edges 0→1 (2), 0→2 (2), 1→3 (1), 2→3 (1), 1→4 (4), 2→4 (5), 3→4 (3), 3→5 (4), 4→5 (1). Count the number of…
- On vertices 0..4 a weighted directed graph has these edges, stored in the order shown in the code: (3→4, −2), (2→4, 8), (4→1, 2), (1→3…