#2472
Maximum Number of Non-overlapping Palindrome Substrings
HardTwo PointersStringDynamic ProgrammingGreedyDynamic ProgrammingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n²) |
💡
Intuition
Time O(n²)Space O(n²)
The optimal approach uses dynamic programming to efficiently track palindromic substrings and their counts. This reduces the need for repeated checks and allows us to build on previously computed results.
⚙️
Algorithm
4 steps- 1Step 1: Create a 2D array dp where dp[i][j] is true if the substring s[i...j] is a palindrome.
- 2Step 2: Fill the dp array using a bottom-up approach, checking substrings of increasing lengths.
- 3Step 3: Create a 1D array count to store the maximum number of non-overlapping palindromic substrings ending at each index.
- 4Step 4: For each index, check if a valid palindrome ends there and update the count array accordingly.
solution.py19 lines
1# Full working Python code
2
3def max_palindromic_substrings(s, k):
4 n = len(s)
5 dp = [[False] * n for _ in range(n)]
6 count = [0] * n
7
8 for length in range(1, n + 1):
9 for i in range(n - length + 1):
10 j = i + length - 1
11 if s[i] == s[j] and (length <= 2 or dp[i + 1][j - 1]):
12 dp[i][j] = True
13 if length >= k:
14 count[j] = max(count[j], (count[i - 1] if i > 0 else 0) + 1)
15
16 return count[-1]
17
18# Example usage
19print(max_palindromic_substrings('abaccdbbd', 3)) # Output: 2ℹ
Complexity note: The time complexity is O(n²) due to the nested loops used to fill the dp array, but it is more efficient than brute force as it avoids redundant palindrome checks.
- 1Identifying palindromic substrings is crucial; use dynamic programming for efficiency.
- 2Non-overlapping substrings require careful tracking of indices to avoid counting overlaps.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.