heights.
Every night, each seedling that is **strictly shorter** than its left neighbour (the nearest one still in the row) withers. All such seedlings wither at the same time, and in the morning the row closes up: the withered ones are removed and the survivors get new neighbours.
How many nights pass before the row stops changing, that is, before the heights from left to right become non-decreasing? If the row is already like that, the answer is 0.
A direct night-by-night simulation can take O(n²); try to do it in O(n).heights=[6, 2, 4, 1, 7] → 2
On the first night 2 (next to 6) and 1 (next to 4) wither, leaving [6, 4, 7]. On the second night 4 (next to 6) withers, leaving [6, 7], which never changes again. The answer is 2.
heights=[1, 3, 3, 8] → 0
No plant is shorter than its left neighbour, so the row is already settled.
heights=[9, 1, 2, 3] → 3
Exactly one plant withers each night: first 1, then 2, then 3, since each time the new neighbour of 9 is shorter than it.
heights=[6, 2, 4, 1, 7]
2
Run checks the first 3 tests in your browser. Submit checks all 128 tests on the server, hidden ones included.