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: Transform String for Optimal SegmentationInput: s = "abaca"k = 2 (max distinct chars)Process: Try ChangesTest each position changeOutput: 3Maximum partitionsOriginal: a|b|ac|a = 3Try: change c→b: ab|ab|a = 3Best: 3 partitions(a), (b), (a,c)(a,b), (a,b), (a)Optimal resultEach partition has ≤ k distinct characters
Understanding the Visualization
1
Input
String s="abaca" with k=2 (max 2 distinct chars per partition)
2
Process
Try changing each character and find optimal partitioning
3
Output
Maximum number of partitions achievable
Key Takeaway
🎯 Key Insight: Try each possible character change and greedily partition to maximize segments
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