Data Structures & AlgorithmsVery hardICPC regional · DP counting

Problem: How many longest increasing subsequences does [1, 3, 5, 4, 7] have? Run the DP that counts both length and number of optimal subsequences.

Problem: How many longest increasing subsequences does [1, 3, 5, 4, 7] have? Run the DP that counts both length and number of optimal subsequences.
a = [1, 3, 5, 4, 7]
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?
  1. A. 1
  2. B. 3
  3. C. 2
  4. D. 4

Correct answer: C. 2

The length is 4, achieved by 1,3,5,7 and 1,3,4,7. Ties in length must be summed, not overwritten.

More Coding Interview Problems questions

Exams that ask this topic