Repaint Tiles for the Longest Run
Medium · Sliding Window · about 25 min
A row of floor tiles is written as a string tiles of capital letters, one letter per tile color. A painter may repaint at most k tiles, each to any color.
Return the length of the longest stretch of neighbouring tiles that can all be the same color after the repaints.
Examples:
longest_after_repaints("ABAB", 2) → 4 (repaint both B tiles)
longest_after_repaints("AABABBA", 1) → 4 ("AABA" becomes "AAAA")
An empty row gives 0. k is 0 or more. Aim for O(n).
Hints
- For any window, the cheapest plan is to repaint everything that is not its most common color.
- So a window is fine while its length minus the count of its top color is at most k.
- Grow the right edge; when the window needs too many repaints, move the left edge forward and lower that tile's count.
Learn the pattern first: the Sliding Window lesson.
More Sliding Window problems
- Food Stall Moving Average (Easy)
- Badge Scanned Twice Too Soon (Easy)
- Longest Stretch With No Repeat Song (Medium)
- Scrambled Code Hidden in a Log (Medium)
- Fewest Orders to Hit the Goal (Medium)
- Shortest Note That Covers Every Letter (Hard)
- Rolling Peak of a Sensor (Hard)