Keep the Window Valid: Most Common Plus a Budget
A path is laid with coloured tiles: red, red, green, red, blue, red, red (RRGRBRR). A painter may repaint at most one tile. What is the longest run of same-coloured tiles they can end up with? The window idea from the last lesson still works. The only new skill is writing down, in one line, what makes a window "valid".
The rule
A window is valid when its size minus its most common count fits the budget.
Inside any stretch of tiles, the cheapest way to make them all one colour is to keep the colour that already appears most and repaint the rest. So the repaints needed are size − count of the most common colour. If that number is at most k, the stretch can be made uniform. Everything else is the grow-and-shrink loop, with a dictionary of colour counts as the thing the window tracks:
def longest_after_repaints(tiles, k):
counts = {}
left = best = 0
for right, colour in enumerate(tiles):
counts[colour] = counts.get(colour, 0) + 1
while (right - left + 1) - max(counts.values()) > k: # too many repaints
counts[tiles[left]] -= 1
left += 1
best = max(best, right - left + 1)
return bestWith a handful of colours, max(counts.values()) is quick, so the whole run is one pass. Shrinking is safe for the usual reason: a shorter stretch inside a fixable one never needs more repaints.