Leetcode 2760. Longest Even Odd Subarray With Threshold
You are given an array of integers arr
and an integer threshold
. You need to find the length of the longest subarray where:
threshold
.Return the length of this longest even-odd alternating subarray.
arr
is not empty?arr
all positive integers?Yes, for this problem, you can assume that arr
is not empty and all the elements are positive integers.
0
if no such subarray exists?Yes, return 0
if no such subarray exists, and yes, subarrays of length 1 should be considered, provided they meet the criteria.
threshold
or when the alternating property is violated.public class LongestEvenOddSubarray {
public int longestAlternatingSubarray(int[] arr, int threshold) {
int maxLength = 0;
int currentLength = 0;
int n = arr.length;
for (int i = 0; i < n; i++) {
if (arr[i] > threshold) {
currentLength = 0; // reset length if element exceeds threshold
continue;
}
if (currentLength == 0) {
// Start a new subarray
currentLength = 1;
} else {
int prevElem = arr[i - 1];
if ((prevElem % 2 == 0 && arr[i] % 2 != 0) || (prevElem % 2 != 0 && arr[i] % 2 == 0)) {
currentLength++;
} else {
currentLength = 1; // reset length if alternating pattern is broken
}
}
maxLength = Math.max(maxLength, currentLength);
}
return maxLength;
}
public static void main(String[] args) {
LongestEvenOddSubarray obj = new LongestEvenOddSubarray();
int[] arr = {1, 2, 3, 4, 5};
int threshold = 5;
System.out.println(obj.longestAlternatingSubarray(arr, threshold)); // Output should be 5
}
}
This approach ensures that we efficiently find the longest subarray that alternates between even and odd numbers and does not exceed the given threshold.
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?