Islands
InterviewTime limit1sMemory limit128 MB
Given heights along a line, find the maximum number of separate exposed segments at any single rising water level.
- Level
Medium5 of 10
- Topics
- Sorting, Array, Simulation, Implementation
- Solved
- No attempts yet
Problem
Whenever it rains, Farmer John's field floods. Because the field is not perfectly level, the water rises unevenly, and the exposed land breaks up into a number of disjoint "islands".
The field is a one-dimensional landscape given by consecutive height values . Assume the field is bounded on both ends by walls of effectively infinite height. As a rainstorm fills the field, the lowest regions are covered first, creating a number of separate islands, and eventually everything is submerged. The instant the water level becomes equal to the height of a piece of land, that piece of land is considered underwater.
For example, with the heights , adding just over unit of water leaves islands (the most that ever appear at once); after a total of units of water only islands remain exposed.
Compute the maximum number of islands that are ever visible at a single point in time, as the water rises from empty until the entire field is underwater.
Input
- The first line contains the integer ().
- Each of the next lines contains one height ().
Output
- Print a single integer: the maximum number of islands that appear at any single moment during the storm.
Hint
Consider the heights . When the water level lies strictly between and , only the cells of height or more remain above water, splitting the land into separate islands — the maximum seen at any single instant.