Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (LIS length with O(n²) DP and the number of LIS)
What is printed? (LIS length with O(n²) DP and the number of LIS)
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], C[i] = L[j] + 1, C[j]
elif L[j] + 1 == L[i]: C[i] += C[j]
m = max(L)
print(m, sum(c for l, c in zip(L, C) if l == m))- A. 4 2
- B. 4 1
- C. 3 2
- D. 5 2
Correct answer: A. 4 2
Track both the best length ending at i and how many subsequences achieve it. 1, 3, 5, 7 and 1, 3, 4, 7 both have length 4 → 2. O(n²).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (coin change: number of combinations) python def ways(coins, amt): dp = [1] + [0] amt for c in coins: for a in range(c…
- What is printed? (rod cutting – maximise revenue) python price = [0, 1, 5, 8, 9, 10, 17, 17, 20] n = 8; r = [0] (n + 1) for j in range(1…
- What is printed? (subset sum with a boolean DP table) python a = [3, 34, 4, 12, 5, 2] def can(t): dp = [True] + [False] t for x in a: for…
- What is printed? (egg dropping: minimum trials in the worst case) python def trials(eggs, floors): # dp[m] = max floors checkable with m…
- What is printed? (0/1 knapsack with item reconstruction) python w = [1, 3, 4, 5]; v = [1, 4, 5, 7]; W = 7; n = 4 dp = [[0] (W + 1) for in…
- What is printed? (number of BSTs vs number of binary heaps on keys 1..4) python from math import comb from functools import lrucache…