Skip to content

Commit

Permalink
Max Consecutive Ones III
Browse files Browse the repository at this point in the history
  • Loading branch information
nikoo28 committed May 2, 2024
1 parent c4951be commit 187d6c4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 13 deletions.
26 changes: 13 additions & 13 deletions src/main/java/leetcode/medium/MaxConsecutiveOnesIII.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

}
14 changes: 14 additions & 0 deletions src/test/java/leetcode/medium/MaxConsecutiveOnesIIITest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

0 comments on commit 187d6c4

Please sign in to comment.