Leetcode3201. 找出有效子序列的最大长度 I

Every day a Leetcode

题目来源:3201. 找出有效子序列的最大长度 I

解法1:枚举

全奇数、全偶数、奇偶交替三种情况的最大值即为所求。

代码:

c 复制代码
/*
 * @lc app=leetcode.cn id=3201 lang=cpp
 *
 * [3201] 找出有效子序列的最大长度 I
 */

// @lc code=start
class Solution
{
public:
    int maximumLength(vector<int> &nums)
    {
        // 分三种情况:全奇、全偶、奇偶交替
        int odd = 0, even = 0;
        for (int &num : nums)
        {
            if (num % 2)
                odd++;
            else
                even++;
        }
        int interlaced = 1, tag = nums[0];
        for (int i = 1; i < nums.size(); i++)
            if ((nums[i] & 1) ^ (tag & 1))
            {
                interlaced++;
                tag = nums[i];
            }
        return max(interlaced, max(odd, even));
    }
};
// @lc code=end

结果:

复杂度分析:

时间复杂度:O(n),其中 n 是数组 nums 的长度。

空间复杂度:O(1)。

相关推荐
长安er3 小时前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
元亓亓亓3 小时前
LeetCode热题100--62. 不同路径--中等
算法·leetcode·职场和发展
小白菜又菜4 小时前
Leetcode 1925. Count Square Sum Triples
算法·leetcode
粉红色回忆4 小时前
用链表实现了简单版本的malloc/free函数
数据结构·c++
写代码的小球5 小时前
C++计算器(学生版)
c++·算法
k***92165 小时前
【C++】继承和多态扩展学习
java·c++·学习
序属秋秋秋6 小时前
《Linux系统编程之进程控制》【进程等待】
linux·c语言·c++·进程·系统编程·进程控制·进程等待
l木本I6 小时前
Reinforcement Learning for VLA(强化学习+VLA)
c++·人工智能·python·机器学习·机器人
strive programming6 小时前
Effective C++_异常(解剖挖掘)
c++
POLITE37 小时前
Leetcode 41.缺失的第一个正数 JavaScript (Day 7)
javascript·算法·leetcode