LeetCode 75

Longest Subarray of 1's After Deleting One Element

Problem
LC 1493
Topic
Sliding Window
File
official75_LC1493LongestSubarrayOfOnesAfterDeletingOneElement.java
Path
pkg5leetcode/official75/official75_LC1493LongestSubarrayOfOnesAfterDeletingOneElement.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC1493LongestSubarrayOfOnesAfterDeletingOneElement.java
Approach
Sliding window allow at most one zero.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC1493LongestSubarrayOfOnesAfterDeletingOneElement.java
1package pkg5leetcode.official75;2 3/*4 * Longest Subarray of 1's After Deleting One Element | LC 14935 * APPROACH: Sliding window allow at most one zero.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC1493LongestSubarrayOfOnesAfterDeletingOneElement {9    static int longestSubarray(int[] nums) {10        int l = 0, zeros = 0, best = 0;11        for (int r = 0; r < nums.length; r++) {12            if (nums[r] == 0) zeros++;13            while (zeros > 1) {14                if (nums[l] == 0) zeros--;15                l++;16            }17            best = Math.max(best, r - l);18        }19        return best;20    }21 22    public static void main(String[] args) {23        check(longestSubarray(new int[]{1,1,0,1}) == 3, "case1");24        check(longestSubarray(new int[]{0,1,1,1,0,1,1,0,1}) == 5, "case2");25        check(longestSubarray(new int[]{1,1,1}) == 2, "case3");26        System.out.println("all tests passed");27    }28 29    static void check(boolean cond, String name) {30        if (!cond) throw new AssertionError("FAILED: " + name);31        System.out.println("  PASS " + name);32    }33}