Tetris Remastered
Time limit1sMemory limit512 MB
Given column heights with no gaps underneath, drop 1-by-x horizontal pieces to finish a full n-wide rectangle using the fewest pieces.
- Level
Medium6 of 10
- Topics
- Greedy, Array, Implementation, Simulation
- Solved
- No attempts yet
Problem
Mila likes to play Tetris. Today she learnt about a new game that is similar to Tetris. The new game has an infinite rectangular field with the bottom and width equal to , divided into cells of size . Unlike real Tetris, this game uses horizontal pieces with height and width consisting of cells, that is, pieces of size . Before the next piece starts to fall, a player can choose its size as any integer between and , inclusive. Pieces can't be rotated, but they can be moved left or right. A piece falls until it reaches an occupied cell under it or the bottom of the field.
Mila doesn't like to leave empty cells under the pieces. Her goal is to fill lower rows of the field in the way that all occupied cells form a rectangle of width .
You are given a field state: , where is the number of occupied cells in the -th column of the field. In the given field no empty cell is under the occupied one. For example, if sequence is , the field looks like this:

Find the minimum number of pieces Mila needs to play to occupy the lower rows of the field forming a rectangle of width .
Input
The first line contains a single integer , the width of the field ().
The second line contains integers , the number of occupied cells in each column of the field ().
At least one of the is strictly greater than .
Output
Print a single integer: the minimum number of pieces Mila will need to build a rectangle of width .
Notes
In the example Mila can use the following four pieces:
