-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestEvenOddSubarrayWithThreshold.java
35 lines (29 loc) · 1.17 KB
/
LongestEvenOddSubarrayWithThreshold.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class LongestEvenOddSubarrayWithThreshold {
public int longestAlternatingSubarray(int[] nums, int threshold) {
int result = 0;
int checkCurrentEvenOrOdd = 0;
boolean initialized = true;
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == checkCurrentEvenOrOdd) {
if (initialized) {
result++;
initialized = false;
} else {
if (i < nums.length - 1 && nums[i + 1] != checkCurrentEvenOrOdd && nums[i] <= threshold) {
result++;
checkCurrentEvenOrOdd = checkCurrentEvenOrOdd == 0 ? 1 : 0;
}
else {
initialized = true;
}
}
}
}
return result;
}
public static void main(String[] args) {
LongestEvenOddSubarrayWithThreshold longestEvenOddSubarrayWithThreshold = new LongestEvenOddSubarrayWithThreshold();
int[] nums = new int[]{3, 2, 5, 4};
System.out.println(longestEvenOddSubarrayWithThreshold.longestAlternatingSubarray(nums, 5));
}
}