[LeetCode][JAVA] 1004. Max Consecutive Ones III

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

LeetCode

목록 보기
15/16

I wanted to use sliding window, but it was kind of hard for me to think of a way to change the size of the window.

At first, I thought to save the index of 0 and slide the window size of k. To do that, I had to loop too many times and it didn’t worked. Finally I saw the solution, and it wasn’t straightforward to understand.

After I understood the answer, I wrote the method in my way.

class Solution {
    public int longestOnes(int[] nums, int k) {
        int max = 0;
        int zeros = 0;
        int right;
        int left = 0;

        for (right = 0; right < nums.length; right++) {
            if (nums[right] == 0) zeros++;

            if (zeros > k) {
                if (nums[left] == 0) zeros--;
                left++;
            }

            if (zeros <= k) max = Math.max(max, right - left + 1);
        }

        return max;
    }
}

0개의 댓글