3105: Longest-Strictly-Increasing-or-Strictly-Decreasing-Subarray
Easy
table of contents
Simply just iterate through the array
nums, keeping track of both ans and
counter variables, which tracks the longest
previous strictly monotonic subarray and the
length of the current strictly monotonic
subarray. When iterating through nums, keep track of
the current direction (increasing, decreasing or equal),
check the relationship of nums[i-1] with
nums[i] and respond accordingly (e.g. if
nums[i] was strictly increasing and then suddenly
becomes strictly decreasing, then make
ans = max(ans, counter), reset the counter
variable, and change the direction variable)
code
class Solution {
public:
int longestMonotonicSubarray(vector<int>& nums) {
int ans = 1;
int counter = 1;
int direction = 0;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i-1] != nums[i]) {
if (direction == ((nums[i-1] < nums[i]) ? 1 : -1)) {
++counter;
} else {
direction = (nums[i-1] < nums[i]) ? 1 : -1;
ans = max(ans, counter);
counter = 2;
}
} else {
direction = 0;
ans = max(ans, counter);
counter = 0;
}
}
ans = max(ans, counter);
return ans;
}
};