Skip to content

3201. Find the Maximum Length of Valid Subsequence I

Description

You are given an integer array nums.

A 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

 

Solutions

Solution: Dynamic Programming

  • Time complexity: O(n)
  • Space complexity: O(1)

 

JavaScript

js
/**
 * @param {number[]} nums
 * @return {number}
 */
const maximumLength = function (nums) {
  const dp = Array.from({ length: 2 }, () => new Array(2).fill(0));
  let result = 0;

  for (const num of nums) {
    const remainder = num % 2;

    dp[remainder][0] = dp[0][remainder] + 1;
    dp[remainder][1] = dp[1][remainder] + 1;
    result = Math.max(result, dp[remainder][0], dp[remainder][1]);
  }

  return result;
};

Released under the MIT license