Dare2Solve
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.
nums
.nums
. We only need to iterate through the array once to count evens and odds.let a = 0,
b = 0,
c = 0,
d = 0;
a
: Counter for even numbers.b
: Counter for odd numbers.c
: Length of the valid subsequence ending with the last even number encountered.d
: Length of the valid subsequence ending with the last odd number encountered. for (let num of nums) {
for ... of
loop to iterate through each element num
in the array nums
.if (num % 2 === 0) {
a++;
c = d + 1;
} else {
b++;
d = c + 1;
}
Checks if the current num
is even (num % 2 === 0
):
a
(count of even numbers).c
to d + 1
(length of the subsequence ending with the current even number).If num
is odd:
b
(count of odd numbers).d
to c + 1
(length of the subsequence ending with the current odd number).Ends the for ... of
loop after iterating through all elements of nums
.
return Math.max(a, b, c, d);
a
, b
, c
, and d
using Math.max
.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});
}
};
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)
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));
}
}
/**
* @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);
};