Problem Description
Given an array of integers nums, a subsequence sub (which can be obtained by deleting some or no elements without changing the order) is defined to be "valid" if for every pair of consecutive elements in sub, (sub[i] + sub[i+1]) % 2 is the same across the entire subsequence. In other words, either every adjacent pair sums up to an even number (which happens when both numbers have the same parity) or to an odd number (when the numbers have different parities). The task is to return the length of the longest valid subsequence possible.
Key Insights
- If the common modulo value is 0 then every adjacent pair’s sum is even. This forces every two consecutive numbers to have the same parity; in fact, the entire subsequence must be all even or all odd.
- If the common modulo value is 1 then every consecutive pair sums to odd. This forces the subsequence to alternate parities.
- The maximum valid subsequence will be the best among:
- The subsequence consisting of all even numbers.
- The subsequence consisting of all odd numbers.
- The longest alternating subsequence (respecting the original order).
- A greedy scan is sufficient to extract the longest alternating subsequence from the array.
Space and Time Complexity
Time Complexity: O(n) – We scan the array a constant number of times. Space Complexity: O(1) – Only a few counters and variables are used.
Solution
We consider two cases:
- Constant modulo = 0: The valid subsequence must have all numbers with the same parity. Its maximum possible length is the larger of the counts of even numbers or odd numbers.
- Constant modulo = 1: The valid subsequence needs to alternate parities. We can greedily traverse the array and pick an element if its parity differs from the last chosen element. This produces the longest alternating subsequence possible from the given order. Finally, the answer is the maximum among the two cases above.
Data structures used:
- Simple integer counters for even, odd, and the current length of the alternating sequence. Technique:
- One pass to count evens and odds.
- One pass (greedy) to build the longest alternating subsequence. The overall answer is the maximum of (count_evens, count_odds, alternating_length).