Leetcode 3201. Find the Maximum Length of Valid Subsequence I

  • [Leetcode 3201. Find the Maximum Length of Valid Subsequence I](#Leetcode 3201. Find the Maximum Length of Valid Subsequence I)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题我们注意到,要使得条件成立,那么选择出来的数列在奇数位和偶数位上的数字奇偶性必然相同,因此,我们只需要讨论以下4种情况就行了:

  1. 全为奇数
  2. 全为偶数
  3. 先奇数后偶数
  4. 先偶数后奇数

我们分别讨论一下这四种情况然后取出最大值即可。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def maximumLength(self, nums: List[int]) -> int:
        n = len(nums)
        n1 = len([x for x in nums if x % 2 == 0])
        n2 = len([x for x in nums if x % 2 == 1])
        n3, tgt = 0, 0
        for x in nums:
            if x % 2 == tgt:
                n3 += 1
                tgt = 1-tgt
        n4, tgt = 0, 1
        for x in nums:
            if x % 2 == tgt:
                n4 += 1
                tgt = 1-tgt
        return max(n1, n2, n3, n4)

提交代码评测得到:耗时632ms,占用内存39.6MB。

相关推荐
Espresso Macchiato13 天前
Leetcode 3196. Maximize Total Cost of Alternating Subarrays
leetcode·动态规划·leetcode medium·leetcode周赛403·leetcode 3196
Espresso Macchiato14 天前
Leetcode 3195. Find the Minimum Area to Cover All Ones I
leetcode·leetcode medium·leetcode题解·leetcode 3195·leetcode周赛403
Espresso Macchiato22 天前
Leetcode 3186. Maximum Total Damage With Spell Casting
动态规划·leetcode medium·leetcode题解·leetcode 3186·leetcode周赛402
Espresso Macchiato1 个月前
Leetcode 3175. Find The First Player to win K Games in a Row
leetcode medium·leetcode题解·leetcode 3175·leetcode双周赛132
Espresso Macchiato2 个月前
Leetcode 3143. Maximum Points Inside the Square
leetcode medium·leetcode题解·leetcode双周赛130·leetcode 3143
Espresso Macchiato2 个月前
Leetcode 3128. Right Triangles
leetcode medium·leetcode题解·leetcode 3128·leetcode双周赛129
Espresso Macchiato2 个月前
Leetcode 3137. Minimum Number of Operations to Make Word K-Periodic
leetcode medium·leetcode题解·leetcode 3137·leetcode周赛396
Espresso Macchiato3 个月前
Leetcode 3117. Minimum Sum of Values by Dividing Array
动态规划·leetcode hard·leetcode题解·leetcode 3117·leetcode周赛393
Espresso Macchiato4 个月前
Leetcode 3085. Minimum Deletions to Make String K-Special
滑动窗口·leetcode medium·leetcode题解·leetcode周赛389·leetcode 3085