diff options
author | Jack Sangdahl <[email protected]> | 2025-02-02 22:27:19 -0700 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-02-02 22:27:19 -0700 |
commit | a0030873dabb517594ae0394350d6715071f7fb8 (patch) | |
tree | 0f3f2019f0abd63cb1962db27a594188f7812761 /long_strictly_incr_decr_subarr.c | |
parent | 8a4cccf73263daae2a4c19f2bfa41cf96187ad56 (diff) | |
download | leetcode-a0030873dabb517594ae0394350d6715071f7fb8.tar.gz leetcode-a0030873dabb517594ae0394350d6715071f7fb8.zip |
3105. longest strictly increasing or strictly decreasing subarray
Diffstat (limited to 'long_strictly_incr_decr_subarr.c')
-rw-r--r-- | long_strictly_incr_decr_subarr.c | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/long_strictly_incr_decr_subarr.c b/long_strictly_incr_decr_subarr.c new file mode 100644 index 0000000..9348541 --- /dev/null +++ b/long_strictly_incr_decr_subarr.c @@ -0,0 +1,26 @@ +// 3105. Longest Strictly Increasing or Strictly Decreasing Subarray +#include "leetcode.h" + +/* + * you are given an array of integers 'nums'. return the legnth of the longest + * subarray of 'nums' which is either strictly increasing or strictly + * decreasing. + */ + +int longestMonotonicSubarray(int *nums, int numsSize) { + int ans = 1, inc = 1, dec = 1; + for (int i = 1; i < numsSize; i++) { + bool a = nums[i] > nums[i - 1], b = nums[i] < nums[i - 1]; + inc = a * inc + 1; + dec = b * dec + 1; + ans = fmax(ans, fmax(inc, dec)); + } + return ans; +} + +int main() { + int n1[] = {1, 4, 3, 3, 2}, n2[] = {3, 3, 3, 3}, n3[] = {3, 2, 1}; + printf("%d\n", longestMonotonicSubarray(n1, ARRAY_SIZE(n1))); // expect: 2 + printf("%d\n", longestMonotonicSubarray(n2, ARRAY_SIZE(n2))); // expect: 1 + printf("%d\n", longestMonotonicSubarray(n3, ARRAY_SIZE(n3))); // expect: 3 +} |