#1488

Avoid Flood in The City

expert · 1045 · lc medium +32 · failed · 39% accepted · 2,150 likes · top 18%

Description

There are up to 109 lakes, initially all empty. Each day is described by rains[i]: if rains[i] > 0, that lake fills with rain; if rains[i] == 0, you may choose and drain exactly one lake. Rain on an already-full lake causes a flood, which you must prevent.

Return an array ans of the same length where ans[i] = -1 on rainy days and ans[i] is the lake you drain on dry days. Return an empty array if flooding cannot be avoided. Draining an empty lake is allowed but has no effect.

Example 1:

Input: rains = [1,2,3,4]
Output: [-1,-1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day full lakes are [1,2,3]
After the fourth day full lakes are [1,2,3,4]
There's no day to dry any lake and there is no flood in any lake.

Example 2:

Input: rains = [1,2,0,0,2,1]
Output: [-1,-1,2,1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day, we dry lake 2. Full lakes are [1]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are [2].
After the sixth day, full lakes are [1,2].
It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.

Example 3:

Input: rains = [1,2,0,1,2]
Output: []
Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.
After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.

Code

1
2
3