#3201
Find the Maximum Length of Valid Subsequence I
MediumArrayDynamic ProgrammingCounting elements based on conditions (like parity).Dynamic programming concepts can sometimes apply, but this problem is more about counting.
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution focuses on the parity of numbers instead of generating subsequences. We can count the number of odd and even numbers in the array and determine the longest valid subsequence based on their counts and possible valid patterns.
⚙️
Algorithm
3 steps- 1Step 1: Initialize counters for odd and even numbers.
- 2Step 2: Iterate through the array and count the odd and even numbers.
- 3Step 3: The longest valid subsequence can be formed by using all odd or all even numbers, or by alternating them. Thus, the result is the maximum of the counts of odd and even numbers.
solution.py4 lines
1def maxLengthValidSubsequence(nums):
2 odd_count = sum(1 for num in nums if num % 2 != 0)
3 even_count = len(nums) - odd_count
4 return max(odd_count, even_count)ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the array to count odd and even numbers. The space complexity is O(1) since we are using a fixed amount of extra space regardless of input size.
- 1The validity of the subsequence depends solely on the parity of the numbers.
- 2The longest valid subsequence can be formed by either all odd or all even numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.