File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments