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)。

相关推荐
ceclar12315 分钟前
C++范围操作(2)
开发语言·c++
一个不知名程序员www1 小时前
算法学习入门---vector(C++)
c++·算法
明洞日记1 小时前
【数据结构手册002】动态数组vector - 连续内存的艺术与科学
开发语言·数据结构·c++
福尔摩斯张1 小时前
《C 语言指针从入门到精通:全面笔记 + 实战习题深度解析》(超详细)
linux·运维·服务器·c语言·开发语言·c++·算法
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——两整数之和
算法·leetcode·职场和发展
Dream it possible!2 小时前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树的最小绝对差(85_530_C++_简单)
c++·leetcode·面试
xxxxxxllllllshi2 小时前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
麦烤楽鸡翅3 小时前
简单迭代法求单根的近似值
java·c++·python·数据分析·c·数值分析
sulikey5 小时前
C++ 四十年:一段跨越时代的语言旅程
c++·c++40周年
-森屿安年-5 小时前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode