From 0169283f553c1342e4646ed0c9d2a1d1871af1df Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Mon, 19 Dec 2022 07:34:24 +0400 Subject: [PATCH] feat: add Number of Ways to Select Buildings (#1140) * add Number of Ways to Select Buildings * Update 2222.c add new line at the end * Rename README.md to DIRECTORY.md * Update leetcode/src/2222.c Co-authored-by: Taj * fix review notes Co-authored-by: David Leal Co-authored-by: Taj --- leetcode/DIRECTORY.md | 1 + leetcode/src/2222.c | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 leetcode/src/2222.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 872609c0..05c7c1e8 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -112,5 +112,6 @@ | 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/) | [C](./src/1752.c) | Easy | | 2024 | [Maximize the Confusion of an Exam](https://leetcode.com/problems/maximize-the-confusion-of-an-exam/) | [C](./src/2024.c) | Medium | | 2130 | [Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/) | [C](./src/2130.c) | Medium | +| 2222 | [Number of Ways to Select Buildings](https://leetcode.com/problems/number-of-ways-to-select-buildings/) | [C](./src/2222.c) | Medium | | 2270 | [Number of Ways to Split Array](https://leetcode.com/problems/number-of-ways-to-split-array/) | [C](./src/2270.c) | Medium | | 2304 | [Minimum Path Cost in a Grid](https://leetcode.com/problems/minimum-path-cost-in-a-grid/) | [C](./src/2304.c) | Medium | diff --git a/leetcode/src/2222.c b/leetcode/src/2222.c new file mode 100644 index 00000000..795ff077 --- /dev/null +++ b/leetcode/src/2222.c @@ -0,0 +1,30 @@ +long numberOfWaysForChar(char * s, char c){ + long firstBuildingAppearNumber = 0; + long secondBuildingAppearNumber = 0; + long result = 0; + + int sLength = strlen(s); + for (int i = 0; i < sLength; i++){ + if (s[i] == c){ + result += secondBuildingAppearNumber; + + firstBuildingAppearNumber += 1; + continue; + } + + secondBuildingAppearNumber += firstBuildingAppearNumber; + } + + return result; + +} + +// numberOfWays returns the sum of number ways of selecting first building +// and the number of ways of selecting second building which gives us the +// number of ways of selecting three building such that no +// consecutive buildings are in the same category. +// Runtime: O(n) +// Space: O(n) +long long numberOfWays(char * s){ + return numberOfWaysForChar(s, '0') + numberOfWaysForChar(s, '1'); +}