Python – Algorithm from CodeForces – Bears and Blocks

Hello party people! 🙂

Today I was wondering whether I have forgotten to code in Python after 4 weeks of coding marathon in VBA and I have decided to try a small portion of the weekly challenge from CodeForces!


So, the second part of the challenge looked really easy, even for me, thus I have decided to give it a try. The original challenge is here. This is how it looks like:

B. Bear and Blocks

Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made ofhi identical blocks. For clarification see picture for the first sample.

Limak will repeat the following operation till everything is destroyed.

Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.

Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.


The first line contains single integer n (1 ≤ n ≤ 105).

The second line contains n space-separated integers h1, h2, …, hn (1 ≤ hi ≤ 109) — sizes of towers.


Print the number of operations needed to destroy all towers.

Sample test(s)





The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.

After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.

So, before going to the code, which was even not re-edited once it was working, what did I do? First, I have decided that my data structure would be a list of list and the way to resolve the puzzle would be to make a function, removing the blocks, returning a new structure. The function was going to be ran until the structure existed (e.g. the list of list was with a length that would return a positive boolean 😀 ). True story. The rest was just some time to code it and some time to remember how to get element from a list in Python and plenty of similar searches. Once the structure achieved what I wanted, I have decided to publish it and to watch TV series 🙂

So, here comes the code:

Enjoy it also in GitHub.


Tagged with: , ,