Number of Ways to Select Buildings LeetCode solution in C++
1class Solution {2public:3long long numberOfWays(string s) {4long long a = 0, b = 0,5ans = 0; // a and b are the number of occurances of '1' and '0'6// after the current building respectively.7for (int i = 0; i < s.length(); i++) {8if (s[i] == '1')9a++;10else11b++;12}13long long c = 0, d = 0; // c and d are the number of occurances of '1' and14// '0' before the current building respectively.15for (int i = 0; i < s.length(); i++) {16if (s[i] == '1') { // Counting the sequences of "010"17ans += (d * b);18a--;19c++;20} else { // Counting the sequences of "101"21ans += (a * c);22b--;23d++;24}25}26return ans;27}28};