LeetCode 75
Max Consecutive Ones III
- Problem
- LC 1004
- Topic
- Sliding Window
- File
- official75_LC1004MaxConsecutiveOnesIII.java
- Path
- pkg5leetcode/official75/official75_LC1004MaxConsecutiveOnesIII.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC1004MaxConsecutiveOnesIII.java
- Approach
- Sliding window shrink when zeros exceed k.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Max Consecutive Ones III | LC 10045 * APPROACH: Sliding window shrink when zeros exceed k.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC1004MaxConsecutiveOnesIII {9 static int longestOnes(int[] nums, int k) {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 > k) {14 if (nums[l] == 0) zeros--;15 l++;16 }17 best = Math.max(best, r - l + 1);18 }19 return best;20 }21 22 public static void main(String[] args) {23 check(longestOnes(new int[]{1,1,1,0,0,0,1,1,1,1,0}, 2) == 6, "case1");24 check(longestOnes(new int[]{0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1,0}, 3) == 10, "case2");25 System.out.println("all tests passed");26 }27 28 static void check(boolean cond, String name) {29 if (!cond) throw new AssertionError("FAILED: " + name);30 System.out.println(" PASS " + name);31 }32}