diff options
-rw-r--r-- | adjacent_subarr_detect1.c | 35 | ||||
-rw-r--r-- | adjacent_subarr_detect1.py | 37 |
2 files changed, 72 insertions, 0 deletions
diff --git a/adjacent_subarr_detect1.c b/adjacent_subarr_detect1.c new file mode 100644 index 0000000..2210895 --- /dev/null +++ b/adjacent_subarr_detect1.c @@ -0,0 +1,35 @@ +// 3349. Adjacent Increasing Subarrays Detection I +#include "leetcode.h" + +/* + * given an array 'nums' of 'n' integers and an integer 'k', determine whther + * there exist two adjacent subarrays of length 'k' such that both subarrays are + * strictly increasing. specifically, check if there are two subarrays starting + * at indices 'a' and 'b' ('a < b') where both subarrays 'nums[a..a + k - 1]' + * and 'nums[b..b + k - 1]' are strictly increasing, and the subarrays must be + * adjacent, meaning 'b = a + k'. return true if it is possible to find two such + * subarrays and 'false' otherwise. + */ + +bool hasIncreasingSubarrays(int *nums, int numsSize, int k) { + int inc = 1, prev = 0, max_len = 0; + for (int i = 1; i < numsSize; i++) { + if (nums[i] > nums[i - 1]) + inc++; + else { + prev = inc; + inc = 1; + } + max_len = fmax(max_len, fmax(inc >> 1, fmin(prev, inc))); + if (max_len >= k) + return true; + } + return false; +} + +int main() { + int n1[] = {2, 5, 7, 8, 9, 2, 3, 4, 3, 1}, + n2[] = {1, 2, 3, 4, 4, 4, 4, 5, 6, 7}; + printf("%d\n", hasIncreasingSubarrays(n1, ARRAY_SIZE(n1), 3)); // expect: 1 + printf("%d\n", hasIncreasingSubarrays(n2, ARRAY_SIZE(n2), 5)); // expect: 0 +} diff --git a/adjacent_subarr_detect1.py b/adjacent_subarr_detect1.py new file mode 100644 index 0000000..57bbddf --- /dev/null +++ b/adjacent_subarr_detect1.py @@ -0,0 +1,37 @@ +# 3349. Adjacent Increasing Subarrays Detection I + +""" +given an array 'nums' of 'n' integers and an integer 'k', determine whther +there exist two adjacent subarrays of length 'k' such that both subarrays are +strictly increasing. specifically, check if there are two subarrays starting +at indices 'a' and 'b' ('a < b') where both subarrays 'nums[a..a + k - 1]' +and 'nums[b..b + k - 1]' are strictly increasing, and the subarrays must be +adjacent, meaning 'b = a + k'. return true if it is possible to find two such +subarrays and 'false' otherwise. +""" + + +class Solution(object): + def hasIncreasingSubarrays(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: bool + """ + inc, prev, max_len = 1, 0, 0 + for i in range(1, len(nums)): + if nums[i] > nums[i - 1]: + inc += 1 + else: + prev = inc + inc = 1 + max_len = max(max_len, max(inc >> 1, min(prev, inc))) + if max_len >= k: + return True + return False + + +if __name__ == "__main__": + obj = Solution() + print(obj.hasIncreasingSubarrays(nums=[2, 5, 7, 8, 9, 2, 3, 4, 3, 1], k=3)) + print(obj.hasIncreasingSubarrays(nums=[1, 2, 3, 4, 4, 4, 4, 5, 6, 7], k=5)) |