From 5a210dfaefaa53cfa6f3152c23d992c93e83c4cf Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Sat, 26 Apr 2025 19:27:09 -0600 Subject: 3392. count subarrays of length three with a condition --- count_subarr_len_three_cond.c | 22 ++++++++++++++++++++++ count_subarr_len_three_cond.py | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 count_subarr_len_three_cond.c create mode 100644 count_subarr_len_three_cond.py diff --git a/count_subarr_len_three_cond.c b/count_subarr_len_three_cond.c new file mode 100644 index 0000000..3d61dd8 --- /dev/null +++ b/count_subarr_len_three_cond.c @@ -0,0 +1,22 @@ +// 3392. Count Subarrays of Length Three With a Condition +#include "leetcode.h" + +/* + * given an integer array 'nums', return the number of subarrays of length 3 + * such that the sum of the first and third number equals exactly half of the + * second number. + */ + +int countSubarrays(int *nums, int numsSize) { + int cnt = 0; + for (int i = 1; i < numsSize - 1; ++i) + if (2 * (nums[i - 1] + nums[i + 1]) == nums[i]) + cnt++; + return cnt; +} + +int main() { + int n1[] = {1, 2, 1, 4, 1}, n2[] = {1, 1, 1}; + printf("%d\n", countSubarrays(n1, ARRAY_SIZE(n1))); // expect: 1 + printf("%d\n", countSubarrays(n2, ARRAY_SIZE(n2))); // expect: 0 +} diff --git a/count_subarr_len_three_cond.py b/count_subarr_len_three_cond.py new file mode 100644 index 0000000..cb542bd --- /dev/null +++ b/count_subarr_len_three_cond.py @@ -0,0 +1,22 @@ +# 3392. Count Subarrays of Length Three With a Condition + +""" +given an integer array 'nums', return the number of subarrays of length 3 +such that the sum of the first and third number equals exactly half of the +second number. +""" + + +class Solution(object): + def countSubarrays(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + return sum(l + r << 1 == m for l, m, r in zip(nums, nums[1:], nums[2:])) + + +if __name__ == "__main__": + obj = Solution() + print(obj.countSubarrays(nums=[1, 2, 1, 4, 1])) + print(obj.countSubarrays(nums=[1, 1, 1])) -- cgit v1.2.3