ProgrammingVery hardGATE CS & IT · Infosys

What is printed?

What is printed?
def lps(s):
    n = len(s)
    dp = [[0] * n for _ in range(n)]
    for i in range(n):
        dp[i][i] = 1
    for L in range(2, n + 1):
        for i in range(n - L + 1):
            j = i + L - 1
            if s[i] == s[j]:
                dp[i][j] = dp[i+1][j-1] + 2 if L > 2 else 2
            else:
                dp[i][j] = max(dp[i+1][j], dp[i][j-1])
    return dp[0][n-1]
print(lps('bbbab'), lps('cbbd'))
  1. A. 3 2
  2. B. 4 2
  3. C. 4 1
  4. D. 5 2

Correct answer: B. 4 2

dp[i][j] is the longest palindromic subsequence inside s[i..j]. In bbbab the subsequence bbbb has length 4, and in cbbd the subsequence bb has length 2.

More Python Programming questions

Exams that ask this topic