Similar Problems
Similar Problems not available
Maximum Number Of Non Overlapping Palindrome Substrings  Leetcode Solution
Companies:
LeetCode: Maximum Number Of Non Overlapping Palindrome Substrings Leetcode Solution
Difficulty: Hard
Topics: string dynamicprogramming
Problem Statement:
Given a string s, find the maximum number of nonoverlapping palindromic substrings of s.
Example:
Input: "ababcbacadefegdehijhklij" Output: 7 Explanation: The optimal way to split this string is "ababa", "c", "a", "defegde", "hijh", "kl", "ij", hence a total of 7 substrings.
Solution:
We can solve this problem using dynamic programming. Let's define dp[i] as the maximum number of nonoverlapping palindromic substrings ending at index i in the given string. To calculate dp[i], we can try to extend all the previously calculated palindromes.
For each index i, we can consider two cases:

We can extend a palindrome that ends at i  1 to include i. If s[j:i] is a palindrome (where j = i  length + 1 and length is the length of the palindrome ending at i  1), we can extend this palindrome to include i. In this case, dp[i] will be equal to dp[j1] + 1.

We can consider a palindrome ending at i that does not overlap with any palindrome ending before i. In this case, dp[i] will be equal to dp[i1] + 1.
We need to take the maximum of these two cases and store it in dp[i].
At the end, dp[n1] will give us the maximum number of nonoverlapping palindromic substrings in the given string.
For the implementation, we need to find all the palindromes ending at index i. We can do this by expanding around the center of the palindrome.
Here is the Python code for the solution:
def countSubstrings(s: str) > int: n = len(s) dp = [0] * n
for i in range(n):
# Case 2: consider palindrome ending at i that does not overlap with any palindrome ending before i
dp[i] = dp[i1] + 1
# Case 1: try to extend all previously calculated palindromes
for j in range(i):
length = i  j + 1
if s[j:i+1] == s[j:i+1][::1] and (length <= 2 or dp[j1] != 0):
dp[i] = max(dp[i], dp[j1] + 1)
return dp[n1]
Time Complexity: O(n^2) where n is the length of the given string.
Space Complexity: O(n) as we are storing the dp array of size n.
Maximum Number Of Non Overlapping Palindrome Substrings Solution Code
1