2025-02-03 Daily Challenge
Today I have done leetcode's February LeetCoding Challenge with cpp.
February LeetCoding Challenge 3
Description
Longest Strictly Increasing or Strictly Decreasing Subarray
You are given an array of integers nums. Return the length of the longest subarray of nums which is either strictly increasing or strictly decreasing.
Example 1:
Input: nums = [1,4,3,3,2]
Output: 2
Explanation:
The strictly increasing subarrays of nums are [1], [2], [3], [3], [4], and [1,4].
The strictly decreasing subarrays of nums are [1], [2], [3], [3], [4], [3,2], and [4,3].
Hence, we return 2.
Example 2:
Input: nums = [3,3,3,3]
Output: 1
Explanation:
The strictly increasing subarrays of nums are [3], [3], [3], and [3].
The strictly decreasing subarrays of nums are [3], [3], [3], and [3].
Hence, we return 1.
Example 3:
Input: nums = [3,2,1]
Output: 3
Explanation:
The strictly increasing subarrays of nums are [3], [2], and [1].
The strictly decreasing subarrays of nums are [3], [2], [1], [3,2], [2,1], and [3,2,1].
Hence, we return 3.
Constraints:
1 <= nums.length <= 501 <= nums[i] <= 50
Solution
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
class Solution {
public:
int longestMonotonicSubarray(vector<int>& nums) {
int answer = 1;
int len = 0;
int s = 0;
for(int i = 1; i < nums.size(); ++i) {
if(sgn(nums[i] - nums[i - 1]) != s) {
s = sgn(nums[i] - nums[i - 1]);
len = 1;
}
len += 1;
if(s) answer = max(len, answer);
}
return answer;
}
};
// Accepted
// 868/868 cases passed (3 ms)
// Your runtime beats 8.24 % of cpp submissions
// Your memory usage beats 89.71 % of cpp submissions (27.8 MB)