LeetCode 2765: Longest Alternating Subarray Solution
Master LeetCode problem 2765 (Longest Alternating Subarray), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2765. Longest Alternating Subarray
Problem Explanation
Explanation:
To solve this problem, we can iterate through the input array and check if the current element, the previous element, and their difference follow the alternating pattern. If they do, we increase the length of the current alternating subarray. If the pattern is broken, we update the maximum length found so far and reset the current length. Finally, we return the maximum length found.
- Start with a current length of 2 (minimum length for alternating subarrays).
- Iterate through the input array from the second element.
- Check if the current element, the previous element, and their difference follow the alternating pattern.
- If they do, increment the current length.
- If the pattern is broken, update the maximum length found so far and reset the current length.
- Return the maximum length found.
Time complexity: O(n) Space complexity: O(1)
Solution Code
class Solution {
public int maxAlternatingSubarray(int[] nums) {
int n = nums.length;
int maxLen = -1;
int curLen = 2;
for (int i = 2; i < n; i++) {
if ((nums[i] - nums[i - 1]) * (nums[i - 1] - nums[i - 2]) < 0) {
curLen++;
} else {
maxLen = Math.max(maxLen, curLen);
curLen = 2;
}
}
return Math.max(maxLen, curLen);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2765 (Longest Alternating Subarray)?
This page provides optimized solutions for LeetCode problem 2765 (Longest Alternating Subarray) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2765 (Longest Alternating Subarray)?
The time complexity for LeetCode 2765 (Longest Alternating Subarray) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2765 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2765 in Java, C++, or Python.