Find the Maximum Length of Valid Subsequence I - Problem

๐ŸŽฏ Find the Maximum Length of Valid Subsequence

You are given an integer array nums. Your task is to find the longest valid subsequence where consecutive pairs have a consistent sum pattern.

A subsequence sub of length x is considered valid if:

  • All consecutive pairs have the same parity: (sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x-2] + sub[x-1]) % 2

Key Insight: The sum of two numbers has the same parity if both numbers are even, both are odd, or one is even and one is odd consistently throughout the subsequence.

Example: In [1, 2, 3, 4], the subsequence [1, 2, 3] is valid because (1+2)%2 = 1 and (2+3)%2 = 1.

Input & Output

example_1.py โ€” Basic case
$ Input: [1, 2, 3, 4]
โ€บ Output: 4
๐Ÿ’ก Note: The entire array [1,2,3,4] forms a valid subsequence because all consecutive sums are odd: (1+2)%2=1, (2+3)%2=1, (3+4)%2=1. This gives us the maximum length of 4.
example_2.py โ€” Mixed parities
$ Input: [1, 2, 1, 1, 2, 1, 2]
โ€บ Output: 6
๐Ÿ’ก Note: We can form the subsequence [1,2,1,1,2,1] where consecutive sums alternate between odd and even in a consistent pattern, giving length 6.
example_3.py โ€” Single element
$ Input: [1]
โ€บ Output: 1
๐Ÿ’ก Note: With only one element, the longest valid subsequence has length 1 (no consecutive pairs to check).

Constraints

  • 1 โ‰ค nums.length โ‰ค 103
  • 1 โ‰ค nums[i] โ‰ค 103
  • The array contains positive integers only

Visualization

Tap to expand
๐ŸŽญ Dance Pattern VisualizationInput: [1, 2, 3, 4] โ†’ Dancers: [Red, Blue, Red, Blue]Goal: Find longest sequence with consistent pair-color mixingColor Mixing RulesR+R=B(odd+odd=even)B+B=B(even+even=even)R+B=R(odd+even=odd)Optimal Sequence: All pairs give Red result1R+B=R2B+R=R3R+B=R4๐ŸŽฏ Result: Maximum sequence length = 4All consecutive pairs consistently produce Red (odd sum)
Understanding the Visualization
1
Identify Patterns
Red+Red=Blue, Blue+Blue=Blue (same colors give blue), Red+Blue=Red (different colors give red)
2
Track Sequences
For each mixing pattern, track the longest sequence ending with each color
3
Find Maximum
The answer is the longest sequence among all valid patterns
Key Takeaway
๐ŸŽฏ Key Insight: There are only 3 possible valid dance patterns, and we can efficiently find the longest sequence for each pattern using dynamic programming in O(n) time.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
28.5K Views
Medium Frequency
~25 min Avg. Time
847 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