Rooftop Garden Benchmarking
InterviewTime limit1sMemory limit128 MB
Count, over every building, how many strictly shorter buildings stand to its right before a building at least as tall blocks the view.
- Level
Medium7 of 10
- Topics
- Stack, Array, Implementation, Greedy
- Solved
- No attempts yet
Problem

There are buildings standing in a row in a city. The -th building from the left has height .
Every building manager is diligent and wants to benchmark the rooftop gardens of other buildings. Each manager can look only to the right from their own building, so manager initially wants to see the rooftops of buildings .
The view can be blocked, however. Looking to the right, the moment a manager meets a building whose height is greater than or equal to their own, that building and every building beyond it become invisible. In other words, manager can only see a consecutive run of strictly shorter buildings, and the view is blocked as soon as the first building of height at least appears (that blocking building is not counted either).
Find the total number of rooftop gardens that all managers can benchmark.
For example, consider with heights , illustrated below.
=
= =
= - =
= = = -> viewing direction
= - = = =
= = = = = =
10 3 7 4 12 2 -> building heights
[1][2][3][4][5][6] -> building numbers
- Manager 1 (height 10) sees buildings 2, 3, and 4, but building 5 (height 12) is at least as tall, so the view stops there. → 3
- Manager 2 (height 3) is blocked immediately by building 3 (height 7). → 0
- Manager 3 (height 7) sees only building 4 and is blocked by building 5 (height 12). → 1
- Manager 4 (height 4) is blocked immediately by building 5 (height 12). → 0
- Manager 5 (height 12) sees only building 6. → 1
- Manager 6 is the last building and has nothing to look at. → 0
Therefore the total is .
Input
- The first line contains the number of buildings . ()
- Each of the next lines contains one building height . ()
Output
- Print, on a single line, the total number of rooftop gardens (buildings) that all managers can benchmark.