Kinda similar with another palindrome DP from LeetCode. Feel it, it is a bottom-up DP - palindrome subsequence.
str = input() slen = len(str) dp = [[0 for x in range(slen)] for x in range(slen)] for clen in range(1, slen + 1): for i in range(0, slen - clen + 1): if clen == 1: dp[i][i] = 1 elif clen == 2: dp[i][i + 1] = 2 if str[i] == str[i+1] else 1 else: if str[i] == str[i + clen - 1]: dp[i][i + clen - 1] = dp[i + 1][i + clen - 2] + 2 else: dp[i][i + clen - 1] = max(dp[i + 1][i + clen - 2], dp[i + 1][i + clen - 1], dp[i][i + clen - 2]) #print (str[i:i+clen], dp[i][i + clen - 1]) ret = 1 for i in range(0, slen - 1): len1 = dp[0][i] len2 = dp[i + 1][slen - 1] ret = max(ret, len1 * len2) print (ret)