문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
인덱스가 0부터 시작하는 정수 배열 nums와 정수 threshold가 주어진다.
인덱스 l에서 시작해서 인덱스 r에서 끝나는(0 <= l <= r < nums.length) nums의 가장 긴 부분 배열의 길이를 구해라. 다음 조건을 만족해야 한다.
부분 배열 중 가장 긴 것의 길이를 나타내는 정수를 반환해라.
#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
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;
}
}