diff options
-rw-r--r-- | num_subarr_geq_threshold.c | 30 | ||||
-rw-r--r-- | num_subarr_geq_threshold.py | 33 |
2 files changed, 63 insertions, 0 deletions
diff --git a/num_subarr_geq_threshold.c b/num_subarr_geq_threshold.c new file mode 100644 index 0000000..34d0bb3 --- /dev/null +++ b/num_subarr_geq_threshold.c @@ -0,0 +1,30 @@ +// 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to +// Threshold +#include "leetcode.h" + +/* + * given an array of integers 'arr' and two integers 'k' and 'threshold', return + * the numberof subarrays of size 'k' and average greater than or equal to + * 'threshold' + */ + +int numOfSubarrays(int *arr, int arrSize, int k, int threshold) { + int sum = 0, cnt = 0; + for (int i = 0; i < k; i++) + sum += arr[i]; + if (sum / k >= threshold) + cnt++; + for (int i = k; i < arrSize; i++) { + sum += arr[i] - arr[i - k]; + if (sum / k >= threshold) + cnt++; + } + return cnt; +} + +int main() { + int a1[] = {2, 2, 2, 2, 5, 5, 5, 8}, + a2[] = {11, 13, 17, 23, 29, 31, 7, 5, 2, 3}; + printf("%d\n", numOfSubarrays(a1, ARRAY_SIZE(a1), 3, 4)); // expect: 3 + printf("%d\n", numOfSubarrays(a2, ARRAY_SIZE(a2), 3, 5)); // expect: 6 +} diff --git a/num_subarr_geq_threshold.py b/num_subarr_geq_threshold.py new file mode 100644 index 0000000..22c8173 --- /dev/null +++ b/num_subarr_geq_threshold.py @@ -0,0 +1,33 @@ +# 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to +# Threshold + +""" +given an array of integers 'arr' and two integers 'k' and 'threshold', return +the numberof subarrays of size 'k' and average greater than or equal to +'threshold' +""" + + +class Solution(object): + def numOfSubarrays(self, arr, k, threshold): + """ + :type arr: List[int] + :type k: int + :type threshold: int + :rtype: int + """ + n, total = len(arr), sum(arr[:k]) + cnt = 1 if total / k >= threshold else 0 + for i in range(k, n): + total += arr[i] - arr[i - k] + if total / k >= threshold: + cnt += 1 + return cnt + + +if __name__ == "__main__": + obj = Solution() + print(obj.numOfSubarrays(arr=[2, 2, 2, 2, 5, 5, 5, 8], k=3, threshold=4)) + print( + obj.numOfSubarrays(arr=[11, 13, 17, 23, 29, 31, 7, 5, 2, 3], k=3, threshold=5) + ) |