2760. Longest Even Odd Subarray With Threshold

2760. Longest Even Odd Subarray With Threshold

Question

You are given a 0-indexed integer array nums and an integer threshold.

Find the length of the longest subarray of numsstarting at index l and ending at index r (0 <= l <= r < nums.length) that satisfies the following conditions:

  • nums[l] % 2 == 0
  • For all indices i in the range [l, r - 1]nums[i] % 2 != nums[i + 1] % 2
  • For all indices i in the range [l, r]nums[i] <= threshold

Solution

temp记录当前窗口长度,res记录最大长度。

循环,如果当前数字大于threshold则清空temp。

否则如果当前temp长度为零,则判断当前位置是否为偶数,如是偶数长度加一。

如果当前temp长度不为零,则判断是否与前一个位置不同号。如果是则temp加一,如果为否则重置temp。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int longestAlternatingSubarray(int[] nums, int threshold) {
int res = 0;
int temp = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] <= threshold){
if(temp != 0){
temp = nums[i] % 2 == nums[i-1] % 2 ? 0 : temp + 1;
}
if(temp == 0){
temp = nums[i] % 2 == 0 ? 1 : 0;
}
}
else{
temp = 0;
}
res = Math.max(res, temp);
}
return res;
}
}
Author

Xander

Posted on

2023-07-02

Updated on

2023-07-02

Licensed under

Comments