Candy Cross
Time limit4sMemory limit1024 MB
Given a single column of A, B, C candies and up to N adjacent swaps, find the maximum score from chained row clears.
- Level
Medium5 of 10
- Topics
- Brute force, Simulation, Recursion
- Solved
- No attempts yet
Problem

This problem is a heavily simplified version of a popular candy game, which we call Candy Cross. The board is a single column of cells. Each cell holds a candy of one of three kinds, A, B, or C. You may make up to moves. In each move, you swap two adjacent candies so that a row of at least three equal candies forms. If no move is possible, the game ends.
After a move, every candy that belongs to such a row disappears. If several rows form at once, they all disappear together. The candies above the holes then fall down to fill them. The column is always refilled to full height with new candies. To decide which new candies fall in, imagine the original column copied upward into an infinitely tall column.
Once the holes are filled, a new situation may arise, and the process repeats automatically. Candies in rows disappear, and the holes are refilled. This continues until no rows remain on the board. Then the next move is made.
Scoring is simple. Each time a row of at least three candies appears, whether from your move or from falling candies, you get points, where is the length of the row. A row of three candies gives 1 point, a row of four gives 3 points, and so on.
Write a program that, given the initial column and the maximum number of moves, computes the maximum score you can achieve.
Input
The first line contains the integer , the maximum number of moves (). The second line contains a string of letters (), each one of A, B, or C. This is the initial column, listed from bottom to top. The initial column never has three equal letters in a row. The input is chosen so that no infinite loop of falling candies can occur.
Output
Print a single integer, the maximum score you can achieve.