Leetcode 2765. Longest Alternating Subarray
You need to determine the longest alternating subarray in a given integer array. An alternating subarray is defined as a subarray where the elements alternately increase and decrease.
For example, in the array [1, 3, 2, 4]
, the longest alternating subarray is [1, 3, 2, 4]
.
To fully understand the problem, let’s consider some clarifying questions:
To find the longest alternating subarray, we can use the following strategy:
Here’s the Java implementation based on the above strategy:
public class Solution {
public int longestAlternatingSubarray(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int maxLength = 1; // at least one element
int currentLength = 1;
for (int i = 1; i < nums.length; i++) {
// Check if the current element alternates with the previous one
if ((nums[i] > nums[i - 1] && (i <= 1 || nums[i - 1] < nums[i - 2])) ||
(nums[i] < nums[i - 1] && (i <= 1 || nums[i - 1] > nums[i - 2]))) {
currentLength++;
} else {
currentLength = 2; // reset to at least the last two elements
}
maxLength = Math.max(maxLength, currentLength);
}
return maxLength;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 3, 2, 4, 3, 5};
System.out.println(solution.longestAlternatingSubarray(nums)); // Output: 6
}
}
The time complexity of this solution is O(n), where n is the length of the input array. This is because we only make a single pass through the array, checking elements and updating the current and maximum lengths as we go.
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?