3490. Find The Maximum Length Of Valid Subsequence I¶
Difficulty: Medium
LeetCode Problem View on GitHub
3490. Find the Maximum Length of Valid Subsequence I
Medium
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 * 1051 <= nums[i] <= 107
Solution¶
class Solution {
public int maximumLength(int[] nums) {
int n = nums.length;
ArrayList<Integer> first = new ArrayList<>();
ArrayList<Integer> second = new ArrayList<>();
first.add(nums[0]); second.add(nums[0]);
for(int i = 1; i < n; i++) {
int current = nums[i];
if((current + first.get(first.size() - 1)) % 2 == 1)
first.add(current);
if((current + second.get(second.size() - 1)) % 2 == 0)
second.add(current);
}
int res1 = Math.max(first.size(), second.size());
if(n <= 1)
return res1;
first.clear(); second.clear();
first.add(nums[1]); second.add(nums[1]);
for(int i = 2; i < n; i++) {
int current = nums[i];
if((current + first.get(first.size() - 1)) % 2 == 1)
first.add(current);
if((current + second.get(second.size() - 1)) % 2 == 0)
second.add(current);
}
int res2 = Math.max(first.size() , second.size());
int ans = Math.max(res1, res2);
int even = 0, odd = 0;
for(int i = 0; i < n; i++) {
if(nums[i] % 2 == 0)
even++;
else if(nums[i] % 2 == 1)
odd++;
}
ans = Math.max(ans, even);
ans = Math.max(ans, odd);
return ans;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here