Maximize the Number of Partitions After Operations - Problem

You are given a string s and an integer k. First, you are allowed to change at most one character in s to another lowercase English letter. After that, you need to perform the following partitioning operation until s is empty:

  • Choose the longest prefix of s containing at most k distinct characters.
  • Delete the prefix from s and increase the number of partitions by one.
  • The remaining characters (if any) maintain their initial order.

Return an integer denoting the maximum number of resulting partitions after the operations by optimally choosing at most one character to change.

Input & Output

Example 1 — Basic Case
$ Input: s = "accca", k = 2
Output: 3
💡 Note: Without change: "ac|cc|a" gives 3 partitions. With optimal change s[4]='c': "ac|cc|c" still gives 3 partitions. Maximum is 3.
Example 2 — Change Helps
$ Input: s = "aabaaca", k = 3
Output: 5
💡 Note: Without change: "aabaa|ca" gives 2 partitions. Change s[2]='c': "aa|c|aa|c|a" gives 5 partitions.
Example 3 — Small k
$ Input: s = "abcdef", k = 1
Output: 6
💡 Note: Each character forms its own partition since k=1. Total: 6 partitions regardless of changes.

Constraints

  • 1 ≤ s.length ≤ 500
  • 1 ≤ k ≤ 26
  • s consists of lowercase English letters

Visualization

Tap to expand
Maximize Partitions After Operations INPUT String s: a idx 0 c idx 1 c idx 2 c idx 3 a idx 4 s = "accca" k = 2 k=2 means each partition can have at most 2 distinct characters Allowed: Change at most 1 character before partitioning ALGORITHM STEPS 1 DP with Bitmask Track distinct chars seen 2 Try Each Position Optionally change char 3 Greedy Partition Take longest valid prefix 4 Maximize Count Find optimal change point Optimal: Change idx 2 (c-->b) "accca" --> "abcca" Partition 1: "ab" (a,b) Partition 2: "cc" (c) Partition 3: "a" (a) Time: O(n * 26 * 2^k) Space: O(n * 2^26) FINAL RESULT After changing s[2]: c --> b "ab" P1 "cc" P2 "a" P3 P1: {a, b} = 2 distinct P2: {c} = 1 distinct P3: {a} = 1 distinct All satisfy k=2 limit OUTPUT 3 [OK] Maximum partitions Without change: 2 partitions With optimal change: 3 Key Insight: The DP uses bitmask to track which characters have been seen. At each position, we try all 26 possible character changes (or no change). When distinct count exceeds k, we start a new partition. The key optimization is memoizing states (position, used_change, char_bitmask) to avoid recomputation. TutorialsPoint - Maximize the Number of Partitions After Operations | Optimized Dynamic Programming
Asked in
Google 15 Meta 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen