leetcode 1493. Longest Subarray of 1's After Deleting One Element (the maximum length of '1' after deleting an element)

Please add a picture description

The array nums contains only 0,1. To delete an element in the array (all 1s also delete one).
Returns the length of the longest all-ones subarray after deleting an element.

Ideas:

Because what is required is the length of the sub-array of all 1s,
and one element needs to be deleted. If some 1s are interspersed with a 0, after deleting the 0, two sub-arrays of 1s can be connected.
The length is the sum of the lengths of two subarrays separated by 0.

What if there are multiple 0s in the middle?
The same processing, or the length of the two sub-arrays separated by 0, the length of the sub-array separated by 0 is also 0.

So add two by two (only one element can be deleted, so only two segments) the length of the sub-array separated by 0, and record the maximum value.

There is a special case: no 0, all 1, then the length of the all 1 sub-array is n, but one element must be deleted, so the final length is n-1.

    public int longestSubarray(int[] nums) {
    
    
        int n = nums.length;
        int pre0 = -1;
        int cur0 = findNextZero(0, nums);
        if (cur0 == n) return n - 1; //全1的情况

        int res = 0;
        while (cur0 != n) {
    
    
            int next0 = findNextZero(cur0 + 1, nums);
            int len = (cur0 - pre0 - 1) + (next0 - cur0 - 1); //两头的0去掉
            
            res = Math.max(res, len);
            
            pre0 = cur0;
            cur0 = next0;
        }
        return res;
    }

    int findNextZero(int from, int[] arr) {
    
    
        for (int i = from; i < arr.length; i++) {
    
    
            if (arr[i] == 0) {
    
    
                return i;
            }
        }
        return arr.length;
    }

おすすめ

転載: blog.csdn.net/level_code/article/details/131550676