PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: iceknight1093
Tester: raysh07
Editorialist: iceknight1093
DIFFICULTY:
Cakewalk
PREREQUISITES:
None
PROBLEM:
Given an array, find the length of its longest subarray that has an even number of odd elements.
EXPLANATION:
The constraints allow the simple brute-force solution of iterating over every subarray and then counting the number of odd elements in it.
However, there is also a smarter solution.
First, consider the whole array. If it has an even number of odd elements, the answer is directly N, and we are done.
Otherwise, we have an odd number of odd elements.
Now, consider the leftmost and the rightmost odd element.
If a subarray includes both of them, it will also include every odd element in the array; and we know this count is odd.
So, any valid subarray cannot include both the leftmost and the rightmost odd elements.
This means we have to leave at least one of them out.
But, leaving exactly one of them out will give us an even number of odd elements, which is what we want - so the optimal solution is to either take everything after the first odd element, or everything before the last odd element, whichever is longer.
This is \mathcal{O}(N).
TIME COMPLEXITY:
\mathcal{O}(N) per testcase.
CODE:
Editorialist's code (PyPy3)
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
l, r, ct = -1, -1, 0
for i in range(n):
if a[i]%2 == 1:
r = i
ct += 1
if l == -1: l = i
if ct%2 == 0: print(n)
else: print(max(r, n-1-l))