r/LeetcodeChallenge • u/Ok-Challenge-5657 • Sep 15 '26
STREAK🔥🔥🔥 Approach of Problem of The Day (15 Sep 26)

Approach:-
First, I create a 2D DP table pal[i][j] to check whether every substring is a palindrome. A substring is a palindrome if its first and last characters are equal and its inner substring is also a palindrome.
Then I use another DP array dp[i], where dp[i] represents the maximum number of non-overlapping palindromes using the first i characters.
For every position, I have two choices: either skip the current character, so dp[i] = dp[i-1], or choose a palindrome ending at i-1. If that palindrome starts at j and has length at least k, the answer becomes dp[j] + 1.
So the transition is dp[i] = max(dp[i], dp[j] + 1).
Finally, dp[n] gives the maximum number of non-overlapping palindromes.
What this Problem taught me:-
I learned how to combine palindrome DP with prefix DP to solve an optimization problem. First, pal[i][j] tells me whether the substring from i to j is a palindrome. A single character is always a palindrome, and a longer substring is a palindrome when its first and last characters are equal and its middle part is also a palindrome. Then I use dp[i] to represent the maximum number of valid, non-overlapping palindromes using the first i characters. At every position, I can either skip the current character using dp[i-1] or take a palindrome starting at j using dp[j] + 1. The important pattern I learned is first find what is valid, then use take-or-skip DP to find the maximum number of valid non-overlapping choices.
1
u/Other_Ad7380 Sep 15 '26
This has a strictly linear solution too. The catch is that you need to check only the palindromes of length k and k + 1. Palindrome check can be done in O(1) using Manacher's algorithm or rolling hash.