|
| 1 | +''' |
| 2 | +You are given an integer array nums. |
| 3 | +A subsequence sub of nums with length x is called valid if it satisfies: |
| 4 | + |
| 5 | +(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2. |
| 6 | +Return the length of the longest valid subsequence of nums. |
| 7 | + |
| 8 | +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. |
| 9 | +''' |
| 10 | + |
| 11 | +class Solution: |
| 12 | + def maximumLength(self, nums: List[int]) -> int: |
| 13 | + count_even = 0 |
| 14 | + count_odd = 0 |
| 15 | + for num in nums: |
| 16 | + if num % 2 == 0: |
| 17 | + count_even += 1 |
| 18 | + else: |
| 19 | + count_odd += 1 |
| 20 | + |
| 21 | + even_dp = 0 |
| 22 | + odd_dp = 0 |
| 23 | + for num in nums: |
| 24 | + if num % 2 == 0: |
| 25 | + even_dp = max(even_dp, odd_dp + 1) |
| 26 | + else: |
| 27 | + odd_dp = max(odd_dp, even_dp + 1) |
| 28 | + |
| 29 | + return max(count_even, count_odd, even_dp, odd_dp) |
0 commit comments