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
Valid Subsequence - Maximum Length INPUT Array: nums 1 i=0 2 i=1 3 i=2 4 i=3 Parity Pattern: ODD EVEN ODD EVEN nums = [1, 2, 3, 4] Length: 4 elements ALGORITHM STEPS 1 Track 3 Patterns All odd, all even, alternating 2 Count Elements Odd: 2, Even: 2 3 Check Alternating (odd+even)%2 = same 4 Find Maximum max(odd, even, alt) Pattern Analysis All Odd: [1,3] len=2 All Even: [2,4] len=2 Alternating: [1,2,3,4] len=4 FINAL RESULT Longest Valid Subsequence: 1 2 3 4 Verification: (1+2)%2 = 1 (2+3)%2 = 1 (3+4)%2 = 1 OK OK OK All sums have same parity! Output: 4 Maximum Length Key Insight: For a valid subsequence, (sub[i] + sub[i+1]) % 2 must be constant for all adjacent pairs. This means we have only 3 valid patterns: all odd elements, all even elements, or alternating. Smart pattern tracking: Track count[parity][last_parity] to find the maximum in O(n) time. TutorialsPoint - Find the Maximum Length of Valid Subsequence I | Smart Pattern Tracking Approach
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