Leetcode 3105. Longest Strictly Increasing or Strictly Decreasing Subarray
You are given an array of integers arr
. Write a function to find the length of the longest subarray which is either strictly increasing or strictly decreasing. Subarray is a contiguous part of an array.
Constraints:
1 <= arr.length <= 10^5
-10^9 <= arr[i] <= 10^9
The function signature in Java:
public int longestAlternatingSubarray(int[] arr);
maxLength
: To store the maximum length found for either increasing or decreasing subarrays.increasingLength
and decreasingLength
: For keeping track of the lengths of currently considered strictly increasing and strictly decreasing subarrays.increasingLength
and reset decreasingLength
to 1.decreasingLength
and reset increasingLength
to 1.increasingLength
and decreasingLength
to 1.maxLength
with the maximum value between increasingLength
, decreasingLength
, and the current maxLength
.Here is the Java implementation for the described strategy:
public class Solution {
public int longestAlternatingSubarray(int[] arr) {
if (arr == null || arr.length == 0) return 0;
if (arr.length == 1) return 1;
int maxLength = 1;
int increasingLength = 1;
int decreasingLength = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[i - 1]) {
increasingLength++;
decreasingLength = 1; // reset decreasingLength
} else if (arr[i] < arr[i - 1]) {
decreasingLength++;
increasingLength = 1; // reset increasingLength
} else {
// Element equal to the previous one, so both are reset
increasingLength = 1;
decreasingLength = 1;
}
maxLength = Math.max(maxLength, Math.max(increasingLength, decreasingLength));
}
return maxLength;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] arr = {1, 2, 3, 4, 5};
System.out.println(solution.longestAlternatingSubarray(arr)); // Output is 5 (strictly increasing)
arr = new int[] {5, 4, 3, 2, 1};
System.out.println(solution.longestAlternatingSubarray(arr)); // Output is 5 (strictly decreasing)
arr = new int[] {1, 3, 5, 4, 2};
System.out.println(solution.longestAlternatingSubarray(arr)); // Output is 3 (either 1, 3, 5 or 5, 4, 2)
arr = new int[] {1, 2, 2, 1};
System.out.println(solution.longestAlternatingSubarray(arr)); // Output is 2 (either 1, 2)
}
}
The time complexity of this algorithm is O(n), where n
is the length of the input array arr
. We only traverse the array once, making comparisons and updating variables in constant time.
The space complexity is O(1), as we are using a constant amount of extra space regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?