Leetcode 2765. Longest Alternating Subarray
Leetcode Problem 2765: Longest Alternating Subarray
Given an array of integers nums
, find the length of the longest subarray with alternating even and odd numbers. An alternating subarray starts with an even number and alternates between even and odd numbers until the end.
nums
array?
max_len
) found so far.curr_len
) of the alternating subarray as we traverse the array.curr_len
.curr_len
to max_len
to update the latter if necessary, then reset curr_len
.curr_len
and max_len
is necessary to check if the longest alternating subarray ends at the last element.#include <vector>
#include <algorithm>
using namespace std;
int longestAlternatingSubarray(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0; // edge case: empty array
int max_len = 1; // Minimum length of an alternating subarray is 1
int curr_len = 1; // Starting with the first element
// Traverse through the array
for (int i = 1; i < n; ++i) {
if ((nums[i-1] % 2 == 0 && nums[i] % 2 != 0) || (nums[i-1] % 2 != 0 && nums[i] % 2 == 0)) {
// They alternate
curr_len++;
} else {
// They do not alternate, update max_len and reset curr_len
max_len = max(max_len, curr_len);
curr_len = 1; // Start a new subarray from the current element
}
}
// Final check in case the longest subarray ends at the last element
max_len = max(max_len, curr_len);
return max_len;
}
In this implementation, we leverage a single pass through the input array while maintaining counts of alternating subarray lengths and adjusting as necessary. This solution handles the primary task efficiently with linear complexity.
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?