Leetcode 2760. Longest Even Odd Subarray With Threshold Sure, let’s tackle the LeetCode problem step-by-step.
Given an array of integers nums sorted in non-decreasing order and an integer threshold, return the length of the longest subarray where:
threshold.nums is non-empty.nums can contain negative integers as well.n), but we will assume n can be large, up to 10^5 or so, common in LeetCode problems.current_length) and the maximum subarray length (max_length).current_length.max_length if current_length is greater than the current max_length.#include <vector>
#include <algorithm>
class Solution {
public:
int longestEvenOddSubarray(std::vector<int>& nums, int threshold) {
int n = nums.size();
int max_length = 0;
int current_length = 0;
for (int i = 0; i < n; ++i) {
if (nums[i] <= threshold) {
if (current_length == 0) {
current_length = 1;
} else if ((nums[i - 1] % 2 != nums[i] % 2)) {
current_length++;
} else {
current_length = 1;
}
max_length = std::max(max_length, current_length);
} else {
current_length = 0;
}
}
return max_length;
}
};
n is the number of elements in the array nums. We iterate through the array exactly once.This solution efficiently finds the longest subarray with the described properties. The if conditions handle transitions between even and odd numbers and check for the threshold constraint appropriately.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?