Problem Description
Given an array of integers, find the length of the longest contiguous subarray that is either strictly increasing or strictly decreasing. A strictly increasing subarray means every subsequent element is larger than its previous element, and a strictly decreasing subarray means every subsequent element is smaller than its previous element.
Key Insights
- The problem focuses on contiguous segments (subarrays), not subsequences.
- Both strictly increasing and strictly decreasing patterns need to be tracked simultaneously.
- A single pass through the array suffices by maintaining two counters: one for increasing sequences and one for decreasing sequences.
- When the current element does not continue the strict order (increasing or decreasing), the respective counter resets to 1.
- The maximum length seen while iterating is the answer.
Space and Time Complexity
Time Complexity: O(n) - where n is the length of the array, as we traverse the array once. Space Complexity: O(1) - only a few extra integer variables are used.
Solution
The solution involves a single traversal of the array. Two counters, "increasing" and "decreasing", are used to maintain the current lengths of strictly increasing and strictly decreasing subarrays, respectively. For each element starting from the second one, check if it is greater than the previous element; if yes, increment the increasing counter, otherwise reset it to 1. Similarly, check if the element is less than the previous element to update the decreasing counter. Throughout the traversal, update the maximum length found among both counters. The data structures used are simple integer variables, and the approach is iterative. This method ensures efficient processing with O(n) time and O(1) additional space.