[LeetCode] Number of Ways to Select Buildings

2222. Number of Ways to Select Buildings

You are given a 0-indexed binary string s which represents the types of buildings along a street where:

  • s[i] = ‘0’ denotes that the ith building is an office and
  • s[i] = ‘1’ denotes that the ith building is a restaurant.

As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type.

  • For example, given s = “001101”, we cannot select the 1st, 3rd, and 5th buildings as that would form “011” which is not allowed due to having two consecutive buildings of the same type.

Return the number of valid ways to select 3 buildings.

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
class Solution {
public:
long long numberOfWays(string s) {
int n = s.length();
vector<long long> one(n, 0), zero(n, 0);

for(int i = 0; i < s.length(); i++) {
if(s[i] == '1') one[i]++;
else zero[i]++;
one[i] += (i ? one[i - 1] : 0);
zero[i] += (i ? zero[i - 1] : 0);
}

long long res = 0;

for(int i = 1; i < s.length() - 1; i++) {
if(s[i] == '1') {
res += zero[i-1] * (zero.back() - zero[i]);
} else {
res += one[i-1] * (one.back() - one[i]);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/03/PS/LeetCode/number-of-ways-to-select-buildings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.