Longest Even Odd Subarray With Threshold — LeetCode 2760 Python Solution
- Problem
- #2760
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums = [3,2,5,4], threshold = 5
- Output
- 3
- Explanation
- In this example, we can select the subarray that starts at l = 1 and ends at r = 3 => [2,5,4]. This subarray satisfies the conditions.
Python solution
class Solution:
def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int:
ans, n = 0, len(nums)
for l in range(n):
if nums[l] % 2 == 0 and nums[l] <= threshold:
r = l + 1
while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold:
r += 1
ans = max(ans, r - l)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2), where n is the length of the array nums |
| Space | O(1) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2760. Longest Even Odd Subarray With Threshold is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Sliding Window.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2760. Longest Even Odd Subarray With Threshold?
- LeetCode 2760. Longest Even Odd Subarray With Threshold is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2760. Longest Even Odd Subarray With Threshold?
- The Python solution on this page runs in O(n^2), where n is the length of the array nums.
- What is the space complexity of LeetCode 2760. Longest Even Odd Subarray With Threshold?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2760. Longest Even Odd Subarray With Threshold cover?
- LeetCode 2760. Longest Even Odd Subarray With Threshold is tagged Array and Sliding Window on LeetCode.