aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ways_split_arr_subarr.c29
-rw-r--r--ways_split_arr_subarr.py33
2 files changed, 62 insertions, 0 deletions
diff --git a/ways_split_arr_subarr.c b/ways_split_arr_subarr.c
new file mode 100644
index 0000000..5c32b34
--- /dev/null
+++ b/ways_split_arr_subarr.c
@@ -0,0 +1,29 @@
+// 2750. Ways to Split Array Into Good Subarrays
+#include "leetcode.h"
+
+/*
+ * given a binary array 'nums'. a subarray of an array is good if it contains
+ * exactly one element with the value 1. return an integer denoting the number
+ * of ways to split the array 'nums' into good subarrays. as the number may be
+ * too large, return it 10^9+7. a subarray is contiguous non empty sequence of
+ * elements within an array.
+ */
+
+int numberOfGoodSubarraySplits(int *nums, int numsSize) {
+ long long ans = 0, cnt = 0;
+ for (int i = 0; i < numsSize; i++) {
+ if (!nums[i])
+ cnt += ans > 0;
+ else {
+ ans = ans ? ans * (cnt + 1) % 1000000007 : 1;
+ cnt = 0;
+ }
+ }
+ return ans;
+}
+
+int main() {
+ int n1[] = {0, 1, 0, 0, 1}, n2[] = {0, 1, 0};
+ printf("%d\n", numberOfGoodSubarraySplits(n1, ARRAY_SIZE(n1))); // expect: 3
+ printf("%d\n", numberOfGoodSubarraySplits(n2, ARRAY_SIZE(n2))); // expect: 1
+}
diff --git a/ways_split_arr_subarr.py b/ways_split_arr_subarr.py
new file mode 100644
index 0000000..df65591
--- /dev/null
+++ b/ways_split_arr_subarr.py
@@ -0,0 +1,33 @@
+# 2750. Ways to Split Array Into Good Subarrays
+
+"""
+given a binary array 'nums'. a subarray of an array is good if it contains
+exactly one element with the value 1. return an integer denoting the number
+of ways to split the array 'nums' into good subarrays. as the number may be
+too large, return it 10^9+7. a subarray is contiguous non empty sequence of
+elements within an array.
+"""
+
+
+class Solution(object):
+ def numberOfGoodSubarraySplits(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ ans, lo = 0, -1
+ for hi, i in enumerate(nums):
+ if i == 1:
+ if ans == 0:
+ ans = 1
+ else:
+ ans *= hi - lo
+ ans %= 10**9 + 7
+ lo = hi
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.numberOfGoodSubarraySplits(nums=[0, 1, 0, 0, 1]))
+ print(obj.numberOfGoodSubarraySplits(nums=[0, 1, 0]))