[LeetCode] Minimum Number of Buckets Required to Collect Rainwater from Houses

2086. Minimum Number of Buckets Required to Collect Rainwater from Houses

You are given a 0-indexed string street. Each character in street is either ‘H’ representing a house or ‘.’ representing an empty space.

You can place buckets on the empty spaces to collect rainwater that falls from the adjacent houses. The rainwater from a house at index i is collected if a bucket is placed at index i - 1 and/or index i + 1. A single bucket, if placed adjacent to two houses, can collect the rainwater from both houses.

Return the minimum number of buckets needed so that for every house, there is at least one bucket collecting rainwater from it, or -1 if it is impossible.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int minimumBuckets(string s) {
int n = s.length(), res = 0;
if(n == 1) return s == "H" ? -1 : 0;
if(s[0] == 'H' and s[1] == 'H') return -1;
if(s[n-1] == 'H' and s[n-2] == 'H') return -1;
for(int i = 1; i < n - 1; i++) {
if(s[i] == 'H' and s[i-1] == 'H' and s[i + 1] == 'H') return -1;
}
for(int i = 1; i < n - 1; i++) {
if(s[i] == '.' and s[i-1] == 'H' and s[i + 1] == 'H') {
s[i] = 'B';
s[i-1] = s[i+1] = 'X';
}
}
for(int i = 0; i < n; i++) {
if(s[i] != 'H') continue;
if(i and s[i-1] == 'B') continue;
if(i + 1 < n and s[i + 1] == 'B') continue;
if(i and s[i-1] == '.') s[i-1] = 'B';
else s[i+1] = 'B';
}
return count(begin(s), end(s), 'B');
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/05/PS/LeetCode/minimum-number-of-buckets-required-to-collect-rainwater-from-houses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.