Longest Subarray of 1's After Deleting One Element - LeetCode
주어진 이진 배열 nums에서 하나의 요소를 삭제한 후, 결과 배열에서 연속된 1로만 이루어진 가장 긴 부분 배열의 길이를 찾으며, 이 부분 배열이 없으면 0을 반환해야 합니다.
Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.
Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.
문제 요약:
주어진 이진 배열 nums에서 하나의 요소를 삭제한 후, 결과 배열에서 연속된 1로만 이루어진 가장 긴 부분 배열의 길이를 찾으며, 이 부분 배열이 없으면 0을 반환해야 합니다.
풀이과정:
class Solution {
public int longestSubarray(int[] nums) {
int maxLen = 0;
int currentLen = 0;
int zeroCnt = 0;
for(int i = 0; i < nums.length; i++){
int num = nums[i];
if(num == 1) {
currentLen++;
}else{
zeroCnt++;
while(zeroCnt > 1){
int _num = i - 1 - currentLen;
if(nums[_num] == 0) {
zeroCnt--;
}else{
currentLen--;
}
}
}
maxLen = Math.max(maxLen, currentLen);
}
return maxLen == nums.length ? maxLen -1 : maxLen;
}
}| 724. Find Pivot Index (0) | 2023.11.11 |
|---|---|
| 1732. Find the Highest Altitude (0) | 2023.11.11 |
| 1004. Max Consecutive Ones III (0) | 2023.11.06 |
| 1456. Maximum Number of Vowels in a Substring of Given Length (0) | 2023.11.02 |
| 643. Maximum Average Subarray I (0) | 2023.11.02 |