Skip to content

Commit 89d61a5

Browse files
authored
1488. Avoid Flood in The City (#901)
2 parents 83e46ac + bc33be3 commit 89d61a5

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

1488. Avoid Flood in The City

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public:
3+
vector<int> avoidFlood(vector<int>& rains) {
4+
set<int> zer; // stores indices of days we can dry (rains[i] == 0)
5+
int n = rains.size();
6+
vector<int> ans(n, -1); // result array
7+
unordered_map<int, int> M; // lake -> last day it was filled
8+
9+
for (int i = 0; i < n; i++) {
10+
if (rains[i] == 0) {
11+
// We can dry some lake later
12+
zer.insert(i);
13+
ans[i] = 1; // default, can be updated later
14+
} else {
15+
int lake = rains[i];
16+
// If lake already has water, we need to dry it before raining again
17+
if (M.find(lake) != M.end()) {
18+
int lastRainDay = M[lake];
19+
// Find first zero-day after last rain day
20+
auto up = zer.upper_bound(lastRainDay);
21+
if (up == zer.end()) {
22+
// No zero-day available to dry => flood
23+
return {};
24+
}
25+
// Use that day to dry the lake
26+
ans[*up] = lake;
27+
zer.erase(up);
28+
}
29+
// Update the last rain day for this lake
30+
M[lake] = i;
31+
}
32+
}
33+
return ans;
34+
}
35+
};

0 commit comments

Comments
 (0)