Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= nums.length <= 50
1 <= nums[i] <= 50
Solution
Video explanation
Here is the video explaining this method in detail. Please check it out:
Method 1 - Generate all subarrays
Here is the approach:
- Generate every possible subarray of the given array
nums
- For each subarray, we need to check if it is strictly increasing or strictly decreasing.
- And the length of the longest valid subarray will be the answer
Pseudocode
|
|
Complexity
- ⏰ Time complexity:
O(n^3)
- Generating and checking all subarrays will take
O(n^2)
, and - checking each subarray for being strictly increasing or decreasing will take
O(n)
.
- Generating and checking all subarrays will take
- 🧺 Space complexity:
O(1)
Method 2 - Maintain the increasing and decreasing subarray size counter
To solve the problem of finding the length of the longest subarray that is either strictly increasing or strictly decreasing in an array of integers nums
, follow this updated approach:
- Initialize Variables: Start by initializing variables to keep track of the current and maximum lengths of increasing (
inc
) and decreasing (dec
) subarrays. - Iterate through the Array: Traverse the array and compare each element with the previous one to determine if the current subarray is increasing or decreasing.
- Update Lengths:
- If the current element is greater than the previous one (indicating an increase), increment the length of the increasing subarray and reset the length of the decreasing subarray.
- If the current element is less than the previous one (indicating a decrease), increment the length of the decreasing subarray and reset the length of the increasing subarray.
- If the current element is equal to the previous one, reset both lengths to 1.
- Update Max Length: Throughout the traversal, continuously update the maximum length encountered for both increasing and decreasing subarrays.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the arraynums
, as we are iterating through the array once. - 🧺 Space complexity:
O(1)
, as we are using a constant amount of extra space.