RBY Pop!
Time limit1sMemory limit128 MB
Change exactly one ball's color, then repeatedly remove any run of 4 or more equal adjacent balls; minimize the number left.
- Level
Medium5 of 10
- Topics
- Simulation, Implementation, Stack, Brute force
- Solved
- No attempts yet
Problem
There are balls stuck together in a single vertical column. Each ball is one of three colors: R (red), B (blue), or Y (yellow).
The player may pick one ball and change its color to a different color. After the change, whenever or more balls of the same color are vertically adjacent, that whole consecutive group goes pop! and disappears at once. Where balls disappear, the remaining balls above and below join together into one vertical column again; if this joining once more produces or more consecutive balls of the same color, those balls also pop! in a chain. This chain repeats until no color has or more balls in a row.
Your goal is to change exactly one ball's color so that, after all the chained pops finish, the number of balls that remain (do not disappear) is as small as possible.
For example, in the left state of the figure below, changing the th ball from the top from yellow to blue makes blue balls consecutive, so they pop! Then red balls pop! in a chain, leaving only balls in the end.

Given the colors of the balls in the initial state, find the minimum number of balls left after the chained pops when you change the color of exactly one ball.
It is guaranteed that in the initial state no or more balls of the same color are consecutive.
Input
The first line contains the number of balls ().
Each of the next lines contains the color of one ball, given from top to bottom. Each color is , , or , where is red, is blue, and is yellow.
Output
Print the minimum number of balls that remain without disappearing.