You are given an array of integers nums
. Return the length of the longest subarray ofnums
which is either strictly increasing or strictly decreasing.
LeetCode Problem - 3105
class Solution {
public int longestMonotonicSubarray(int[] nums) {
// Initialize variables to track the length of the increasing and decreasing subarrays
int subArrayIncreasingOrder = 1;
int subArrayDecreasingOrder = 1;
// Iterate through the array to find the longest increasing and decreasing subarrays
for (int i = 0; i < nums.length - 1; i++) {
// Variables to store temporary lengths of increasing and decreasing subarrays
int tempIncreasing = 1;
int tempDecreasing = 1;
// Check if the current element and the next element form an increasing subarray
if (nums[i + 1] > nums[i]) {
tempIncreasing++;
// Continue checking for increasing elements until the trend breaks
for (int j = i + 1; j < nums.length - 1; j++) {
if (nums[j + 1] > nums[j]) {
tempIncreasing++;
} else break;
}
}
// Check if the current element and the next element form a decreasing subarray
else if (nums[i + 1] < nums[i]) {
tempDecreasing++;
// Continue checking for decreasing elements until the trend breaks
for (int j = i + 1; j < nums.length - 1; j++) {
if (nums[j + 1] < nums[j]) {
tempDecreasing++;
} else break;
}
}
// Update the length of the longest increasing and decreasing subarrays
if (tempIncreasing > subArrayIncreasingOrder) {
subArrayIncreasingOrder = tempIncreasing;
} else if (tempDecreasing > subArrayDecreasingOrder) {
subArrayDecreasingOrder = tempDecreasing;
}
} // outer for loop
// Return the maximum length between increasing and decreasing subarrays
return Math.max(subArrayIncreasingOrder, subArrayDecreasingOrder);
}
}
.