[LeetCode][JAVA] 1493. Longest Subarray of 1's After Deleting One Element

탱귤생귤·2023년 12월 30일
0

LeetCode

목록 보기
16/16

https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/?envType=study-plan-v2&envId=leetcode-75

The solution is almost same as 1004. Max Consecutive Ones III.

At first, I tried to find out the array that has only one number, but that was not neccessary.

class Solution {
    public int longestSubarray(int[] nums) {
        int max = 0;
        int left = 0;
        int right;
        int zero = 0;

        //change a size of a window
        for (right = 0; right < nums.length; right++) {
            if (nums[right] == 0) zero++;

            if (zero > 1) {
                if (nums[left] == 0) zero--;
                left++;
            }

            if (zero <= 1) max = Math.max(max, right - left);
        }

        return max == nums.length ? max - 1 : max;
    }
}

0개의 댓글