Skip to content

2760. Longest Even Odd Subarray With Threshold

  • Time: $O(n)$
  • Space: $O(1)$
 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
class Solution {
 public:
  int longestAlternatingSubarray(vector<int>& nums, int threshold) {
    int ans = 0;
    int dp = 0;

    for (int i = 0; i < nums.size(); ++i) {
      if (nums[i] > threshold)
        dp = 0;
      else if (i > 0 && dp > 0 && isOddEven(nums[i - 1], nums[i]))
        // Increase the size of the subarray.
        ++dp;
      else
        // Start a new subarray if the start is valid.
        dp = nums[i] % 2 == 0 ? 1 : 0;
      ans = max(ans, dp);
    }

    return ans;
  }

 private:
  bool isOddEven(int a, int b) {
    return a % 2 != b % 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int longestAlternatingSubarray(int[] nums, int threshold) {
    int ans = 0;
    int dp = 0;

    for (int i = 0; i < nums.length; ++i) {
      if (nums[i] > threshold)
        dp = 0;
      else if (i > 0 && dp > 0 && isOddEven(nums[i - 1], nums[i]))
        // Increase the size of the subarray.
        ++dp;
      else
        // Start a new subarray if the start is valid.
        dp = nums[i] % 2 == 0 ? 1 : 0;
      ans = Math.max(ans, dp);
    }

    return ans;
  }

  private boolean isOddEven(int a, int b) {
    return a % 2 != b % 2;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def longestAlternatingSubarray(self, nums: list[int], threshold: int) -> int:
    ans = 0
    dp = 0

    def isOddEven(a: int, b: int) -> bool:
      return a % 2 != b % 2

    for i, num in enumerate(nums):
      if num > threshold:
        dp = 0
      elif i > 0 and dp > 0 and isOddEven(nums[i - 1], num):
        # Increase the size of the subarray.
        dp += 1
      else:
        # Start a new subarray if the start is valid.
        dp = 1 if num % 2 == 0 else 0
      ans = max(ans, dp)

    return ans