Find the Maximum Length of Valid Subsequence I - Problem

You are given an integer array nums. A subsequence sub of nums with length x is called valid if it satisfies:

(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2

Return the length of the longest valid subsequence of nums.

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Basic Mixed Array
$ Input: nums = [1,2,3,4]
Output: 4
💡 Note: We can select the entire array [1,2,3,4]. Adjacent sums: (1+2)%2=1, (2+3)%2=1, (3+4)%2=1. All have the same parity.
Example 2 — All Same Parity
$ Input: nums = [2,4,6,8]
Output: 4
💡 Note: All numbers are even. We can select all: [2,4,6,8]. Adjacent sums: (2+4)%2=0, (4+6)%2=0, (6+8)%2=0. All even sums.
Example 3 — Small Array
$ Input: nums = [1,3]
Output: 2
💡 Note: Only one pair possible: [1,3]. Sum: (1+3)%2=0. Valid subsequence of length 2.

Constraints

  • 1 ≤ nums.length ≤ 103
  • 1 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Find Maximum Length of Valid Subsequence1234Input: [1,2,3,4]1+2=3 (odd)2+3=5 (odd)3+4=7 (odd)All adjacent sums have same parity!Valid Subsequence[1,2,3,4] → Length = 4Output: 4
Understanding the Visualization
1
Input Array
[1,2,3,4] with mixed even/odd numbers
2
Check Patterns
Test all 4 possible parity patterns for adjacent sums
3
Find Maximum
Return the longest valid subsequence length
Key Takeaway
🎯 Key Insight: Only 4 parity patterns exist - track them efficiently in one pass
Asked in
Google 15 Meta 12 Amazon 10
8.5K Views
Medium Frequency
~15 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen