[LeetCode] Longest Even Odd Subarray With Threshold

아르당·2026년 10월 30일

LeetCode

목록 보기
577/602
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

인덱스가 0부터 시작하는 정수 배열 nums와 정수 threshold가 주어진다.
인덱스 l에서 시작해서 인덱스 r에서 끝나는(0 <= l <= r < nums.length) nums의 가장 긴 부분 배열의 길이를 구해라. 다음 조건을 만족해야 한다.

  • nums[l] % 2 == 0
  • [l, r - 1] 범위 내의 모든 인덱스 i에 대해, nums[i] % 2 != nums[i + 1] % 2
  • [l, r] 범위 내의 모든 인덱스 i에 대해, nums[i] <= threshold

부분 배열 중 가장 긴 것의 길이를 나타내는 정수를 반환해라.

Example

#1
Input: nums = [3, 2, 5, 4], threshold = 5
Output: 3

#2
Input: nums = [1, 2], threshold = 2
Output: 1

#3
Input: nums = [2, 3, 4, 5], threshold = 4
Output: 3

Constraints

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
  • 1 <= threshold <= 100

Solved

class Solution {
    public int longestAlternatingSubarray(int[] nums, int threshold) {
        int max = 0;
        int n = 0;

        for(int i = 0; i < nums.length; i++){
            int num = nums[i];

            if(num > threshold){
                n = 0;
            }else if(n == 0){
                n = num % 2 == 0 ? 1 : 0;
            }else if(num % 2 != nums[i - 1] % 2){
                n++;
            }else{
                n = num % 2 == 0 ? 1 : 0;
            }

            max = Math.max(max, n);
        }

        return max;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글