[LeetCode] Longest Even Odd Subarray With Threshold

6909. Longest Even Odd Subarray With Threshold

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

Find the length of the longest subarray of nums starting 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

Return an integer denoting the length of the longest such subarray.

Note: A subarray is a contiguous non-empty sequence of elements within an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int longestAlternatingSubarray(vector<int>& nums, int threshold) {
int res = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] % 2 == 1 or nums[i] > threshold) continue;
int j = i + 1;
res = max(res, 1);
for(; j < nums.size(); j++) {
if(nums[j] > threshold) break;
if(nums[j] % 2 == nums[j-1] % 2) break;
res = max(res, j - i + 1);
}
i = j - 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/02/PS/LeetCode/longest-even-odd-subarray-with-threshold/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.