From 187d6c4e72857b300ec774a614b1e3a447354a2e Mon Sep 17 00:00:00 2001 From: Nikhil Lohia Date: Wed, 1 May 2024 18:54:58 -0700 Subject: [PATCH] Max Consecutive Ones III --- .../medium/MaxConsecutiveOnesIII.java | 26 +++++++++---------- .../medium/MaxConsecutiveOnesIIITest.java | 14 ++++++++++ 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/src/main/java/leetcode/medium/MaxConsecutiveOnesIII.java b/src/main/java/leetcode/medium/MaxConsecutiveOnesIII.java index d72279b..dfb572e 100644 --- a/src/main/java/leetcode/medium/MaxConsecutiveOnesIII.java +++ b/src/main/java/leetcode/medium/MaxConsecutiveOnesIII.java @@ -4,24 +4,24 @@ public class MaxConsecutiveOnesIII { int longestOnes(int[] nums, int k) { + int zeroCount = 0; int start = 0; - int end = 0; - int zeros = 0; + int max_ones = 0; + + for (int end = 0; end < nums.length; end++) { + if (nums[end] == 0) + zeroCount++; + + while (zeroCount > k) { + if (nums[start] == 0) + zeroCount--; - while (end < nums.length) { - if (nums[end] == 0) { - zeros++; - } - end++; - if (zeros > k) { - if (nums[start] == 0) { - zeros--; - } start++; } - } - return end - start; + max_ones = Math.max(max_ones, end - start + 1); + } + return max_ones; } } diff --git a/src/test/java/leetcode/medium/MaxConsecutiveOnesIIITest.java b/src/test/java/leetcode/medium/MaxConsecutiveOnesIIITest.java index 949db4b..7bbb581 100644 --- a/src/test/java/leetcode/medium/MaxConsecutiveOnesIIITest.java +++ b/src/test/java/leetcode/medium/MaxConsecutiveOnesIIITest.java @@ -39,4 +39,18 @@ void testLongestOnes4() { int k = 2; assertEquals(2, maxConsecutiveOnesIII.longestOnes(nums, k)); } + + @Test + void testLongestOnes5() { + int[] nums = {0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1}; + int k = 3; + assertEquals(10, maxConsecutiveOnesIII.longestOnes(nums, k)); + } + + @Test + void testLongestOnes6() { + int[] nums = {0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}; + int k = 2; + assertEquals(6, maxConsecutiveOnesIII.longestOnes(nums, k)); + } } \ No newline at end of file