commit a0030873dabb517594ae0394350d6715071f7fb8
parent 8a4cccf73263daae2a4c19f2bfa41cf96187ad56
Author: Jack Sangdahl <jack@pngu.org>
Date: Sun, 2 Feb 2025 22:27:19 -0700
3105. longest strictly increasing or strictly decreasing subarray
Diffstat:
2 files changed, 55 insertions(+), 0 deletions(-)
diff --git a/long_strictly_incr_decr_subarr.c 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
+}
diff --git a/long_strictly_incr_decr_subarr.py b/long_strictly_incr_decr_subarr.py
@@ -0,0 +1,29 @@
+# 3105. Longest Strictly Increasing or Strictly Decreasing Subarray
+
+"""
+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.
+"""
+
+
+class Solution(object):
+ def longestMonotonicSubarray(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ n, ans, inc, dec = len(nums), 1, 1, 1
+ for i in range(1, n):
+ a, b = nums[i] > nums[i - 1], nums[i] < nums[i - 1]
+ inc = a * inc + 1
+ dec = b * dec + 1
+ ans = max(ans, dec, inc)
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.longestMonotonicSubarray(nums=[1, 4, 3, 3, 2]))
+ print(obj.longestMonotonicSubarray(nums=[3, 3, 3, 3]))
+ print(obj.longestMonotonicSubarray(nums=[3, 2, 1]))