#3105
Easy Algorithms Longest strictly increasing or strictly decreasing subarray
Array
64.9% acceptance
Feb 23, 2026
659
33
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn longest_monotonic_subarray(nums: Vec<i32>) -> i32 {
let n = nums.len();
if n == 0 {
return 0;
}
let mut inc = 1i32;
let mut dec = 1i32;
let mut ans = 1i32;
for i in 1..n {
if nums[i] > nums[i - 1] {
inc += 1;
dec = 1;
} else if nums[i] < nums[i - 1] {
dec += 1;
inc = 1;
} else {
inc = 1;
dec = 1;
}
ans = ans.max(inc).max(dec);
}
ans
}
}