2025-07-16 Daily Challenge

Today I have done leetcode's July LeetCoding Challenge with cpp.

July LeetCoding Challenge 16

Description

Find the Maximum Length of Valid Subsequence I

You are given an integer array nums.

A subsequence sub of nums with length x is called valid if it satisfies:

  • (sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.

Return the length of the longest valid subsequence of nums.

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.

 

Example 1:

Input: nums = [1,2,3,4]

Output: 4

Explanation:

The longest valid subsequence is [1, 2, 3, 4].

Example 2:

Input: nums = [1,2,1,1,2,1,2]

Output: 6

Explanation:

The longest valid subsequence is [1, 2, 1, 2, 1, 2].

Example 3:

Input: nums = [1,3]

Output: 2

Explanation:

The longest valid subsequence is [1, 3].

 

Constraints:

  • 2 <= nums.length <= 2 * 105
  • 1 <= nums[i] <= 107

Solution

class Solution {
public:
  int maximumLength(vector<int>& nums) {
    // dp[sum][parity]
    vector<vector<int>> length(2, vector<int>(2));
    for(auto n : nums) {
      int parity = n & 1;
      length[0][parity] = length[0][parity] + 1;
      length[1][parity] = length[1][!parity] + 1;
    }
    return max({length[0][0], length[0][1], length[1][0], length[1][1]});
  }
};

// Accepted
// 951/951 cases passed (8 ms)
// Your runtime beats 42.06 % of cpp submissions
// Your memory usage beats 30 % of cpp submissions (96.4 MB)