[JAVA 문제 풀이] 381. Find the Maximum Length of Valid Subsequence I

[유효한 하위 시퀀스의 최대 길이 찾기 I]
Stupefyee's avatar
Jul 16, 2025
[JAVA 문제 풀이] 381. Find the Maximum Length of Valid Subsequence I
notion image
notion image
정수 배열 'nums'가 주어집니다. 길이가 x인 'nums'의 후속 'sub'가 다음을 만족하면 유효하다고 합니다: * (sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1] % 2. 'nums'의 가장 긴 유효 부분 수열의 길이를 반환합니다. 서브시퀀스는 나머지 요소의 순서를 변경하지 않고 일부 또는 전혀 요소를 삭제하여 다른 배열에서 도출할 수 있는 배열입니다. 제약 조건: * 2 <= nums.length <= 2 * 105 * 1 <= nums [i] <= 107
 

내가 작성한 코드

class Solution { public int maximumLength(int[] nums) { int countOdd = 0; // 홀수 카운트 int countEven = 0; // 짝수 카운트 int countEO = 1; // 홀짝 교차 카운트 (시작은 1로 설정) // 배열 길이가 2보다 작으면 홀짝 교차 카운트는 0 if (nums.length < 3) { return nums.length; } // 홀짝 카운트 for (int i = 0; i < nums.length; i++) { if (nums[i] % 2 == 0) { countEven++; } else { countOdd++; } } // 홀짝 교차 카운트 for (int i = 1; i < nums.length; i++) { if ((nums[i - 1] % 2) != (nums[i] % 2)) { countEO++; } } return Math.max(countEO, Math.max(countOdd, countEven)); } }
 

다른 사람의 코드

class Solution { public int maximumLength(int[] nums) { // 홀 짝 번갈아나오기 각각 세기 // c = nums[0] % 2; >> 첫 번째 숫자의 홀짝을 기준으로 설정 int c = nums[0] % 2, odd = 0, even = 0, both = 0; for (int num : nums) { if (num % 2 == 0) { even++; } else { odd++; } if (num % 2 == c) { both++; c = 1 - c; // 홀짝 변경 } } return Math.max(both, Math.max(even, odd)); } }
 
Share article

stupefyee