3201. Find the Maximum Length of Valid Subsequence I

Dare2Solve

Dare2Solve

3201. Find the Maximum Length of Valid Subsequence I
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Intuition

To find the longest valid subsequence where the sum of every adjacent pair modulo 2 is the same, we can leverage properties of even and odd numbers. Specifically, sequences of even or odd numbers will satisfy the condition trivially.

Approach

  1. Counting Evens and Odds: First, count the number of even and odd numbers in the array nums.
  2. Longest Subsequence Calculation: The longest valid subsequence can be formed by selecting either all even numbers or all odd numbers. Hence, the length of the longest valid subsequence will be the maximum of the count of even numbers or the count of odd numbers.

Complexity

Code Explanation

Initialization

let a = 0,
  b = 0,
  c = 0,
  d = 0;

Loop through Array

    for (let num of nums) {

Conditional Logic

if (num % 2 === 0) {
  a++;
  c = d + 1;
} else {
  b++;
  d = c + 1;
}

Return Statement

return Math.max(a, b, c, d);

Code

C++

class Solution {
public:
    int maximumLength(vector<int>& nums) {
        int a = 0, b = 0, c = 0, d = 0;
        for (int num : nums) {
            if (num % 2 == 0) {
                a++;
                c = d + 1;
            } else {
                b++;
                d = c + 1;
            }
        }
        return max({a, b, c, d});
    }
};

Python

class Solution:
    def maximumLength(self, nums: List[int]) -> int:
        a, b, c, d = 0, 0, 0, 0
        for num in nums:
            if num % 2 == 0:
                a += 1
                c = d + 1
            else:
                b += 1
                d = c + 1
        return max(a, b, c, d)

Java

class Solution {
    public int maximumLength(int[] nums) {
        int a = 0, b = 0, c = 0, d = 0;
        for (int num : nums) {
            if (num % 2 == 0) {
                a++;
                c = d + 1;
            } else {
                b++;
                d = c + 1;
            }
        }
        return Math.max(Math.max(a, b), Math.max(c, d));
    }
}

JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var maximumLength = function(nums) {
    let a = 0, b = 0, c = 0, d = 0;
    for (let num of nums) {
        if (num % 2 === 0) {
            a++;
            c = d + 1;
        } else {
            b++;
            d = c + 1;
        }
    }
    return Math.max(a, b, c, d);
};