[LeetCode] Longest Strictly Increasing or Strictly Decreasing Subarray

3105. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int longestMonotonicSubarray(vector<int>& nums) {
int res = 1, l = 0, r = 0, n = nums.size();
auto judge = [&](int p) {
if(nums[p] == nums[p+1]) return -1;
return nums[p] < nums[p+1] ? 1 : 0;
};
while(l + 1 < n) {
r = l + 1;
if(nums[l] != nums[r]) {
bool inc = judge(l);
while(r + 1 < n and judge(r) == inc) r++;
res = max(res, r - l + 1);
}
l = r;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/04/09/PS/LeetCode/longest-strictly-increasing-or-strictly-decreasing-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.