Longest Repeated Letter Block with Adjacent Swaps
Problem statement
You are given a string s and a non-negative integer k. In one operation, swap the characters at two adjacent positions.
After at most k operations, choose any letter and any contiguous block consisting only of that letter. Return the maximum possible length of such a block.
You may leave some occurrences of the chosen letter outside the block. Characters cannot be inserted, deleted, or replaced, and each adjacent swap costs one operation. You do not have to use the entire budget.
Practice domain
For this exercise, assume s is nonempty and contains only lowercase English letters. The result is the block length, not a transformed string.
Function
longestRepeatedBlock(s: String, k: int) → intExamples
Example 1
s = "aabaa"k = 2return = 4Swap the middle b rightward twice: aabaa → aaaba → aaaab. The four as form one block. No block can have length five because the string has only four copies of a.
Example 2
s = "ababa"k = 1return = 2One swap can produce aabba, whose longest block has length two. Gathering all three as requires two adjacent swaps, so length three is unavailable.
Example 3
s = "abcabc"k = 0return = 1With no swaps allowed, every existing block has length one.
Constraints
- For this exercise, assume
1 <= s.length <= 2000. scontains only characters fromathroughz.- For this exercise, assume
0 <= k <= 10^9.