Intuition
Walk through the array once, keeping the length of the strictly increasing run and the strictly decreasing run that end at the current element; the answer is the longest run ever seen.
Explanation
Key idea
Any strictly increasing (or decreasing) subarray is built one neighbour comparison at a time. If nums[i] > nums[i-1], an increasing run that was ending at i-1 can be extended by one to end at i. The same logic applies to decreasing runs. So we never need to re-scan. We carry two running counters as we move right.
Walk-through
We keep three numbers, all starting at 1:
inc: length of the strictly increasing run ending at the current index,dec: length of the strictly decreasing run ending at the current index,ans: the best run length seen so far.
For each i from 1 to the end, compare nums[i] with nums[i-1]:
nums[i] > nums[i-1]→ the increasing run grows:inc = inc + 1, and the decreasing run breaks:dec = 1.nums[i] < nums[i-1]→ the decreasing run grows:dec = dec + 1, and the increasing run breaks:inc = 1.nums[i] == nums[i-1]→ neither run can continue (strictness is violated), so reset both:inc = 1,dec = 1.
After each step, update ans = max(ans, inc, dec).
Worked example
Take nums = [1,4,3,3,2] (start: inc = dec = ans = 1):
i=1:4 > 1→inc = 2,dec = 1,ans = 2.i=2:3 < 4→dec = 2,inc = 1,ans = 2.i=3:3 == 3→ resetinc = 1,dec = 1,ans = 2.i=4:2 < 3→dec = 2,inc = 1,ans = 2.
The answer is 2, from the increasing run [1,4] or a decreasing run such as [4,3].
Complexity
- Time: O(n). A single pass with constant work per element.
- Space: O(1). Only three counters, regardless of input size.
Implementation
class Solution {
public int longestMonotonicSubarray(int[] nums) {
int ans = 1, inc = 1, dec = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
inc++;
dec = 1;
} else if (nums[i] < nums[i - 1]) {
dec++;
inc = 1;
} else {
inc = 1;
dec = 1;
}
ans = Math.max(ans, Math.max(inc, dec));
}
return ans;
}
}