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 Macchiato8 小时前
Leetcode 3568. Minimum Moves to Clean the Classroom
剪枝·广度优先遍历·leetcode medium·堆排·leetcode周赛452·leetcode 3568
Espresso Macchiato4 天前
Leetcode 3567. Minimum Absolute Difference in Sliding Submatrix
leetcode·leetcode medium·leetcode周赛452·leetcode 3567
Espresso Macchiato4 天前
Leetcode 3566. Partition Array into Two Equal Product Subsets
动态规划·leetcode medium·leetcode 3566·leetcode周赛452
Espresso Macchiato10 天前
Leetcode 3557. Find Maximum Number of Non Intersecting Substrings
动态规划·leetcode medium·leetcode 3557·leetcode双周赛157
Espresso Macchiato18 天前
Leetcode 3552. Grid Teleportation Traversal
广度优先遍历·leetcode medium·leetcode周赛450·leetcode 3552·堆排
Espresso Macchiato19 天前
Leetcode 3551. Minimum Swaps to Sort by Digit Sum
leetcode·排序·leetcode medium·leetcode 3551·leetcode周赛450
Espresso Macchiato22 天前
Leetcode 3543. Maximum Weighted K-Edge Path
leetcode·leetcode medium·图遍历·leetcode 3543·leetcode双周赛156
Espresso Macchiato1 个月前
Leetcode 3532. Path Existence Queries in a Graph I
leetcode medium·dsu·leetcode 3532·leetcode周赛447·uf
Espresso Macchiato1 个月前
Leetcode 3523. Make Array Non-decreasing
leetcode··leetcode medium·leetcode 3523·leetcode周赛446
Espresso Macchiato5 个月前
Leetcode 3418. Maximum Amount of Money Robot Can Earn
leetcode·动态规划·leetcode medium·leetcode 3418·leetcode周赛432