Skip to content

Commit cffedbe

Browse files
committed
Arrays and Strings: Max Consecutive Ones III
1 parent 77a5498 commit cffedbe

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
export function longestOnes(nums: number[], k: number): number {
2+
const n = nums.length;
3+
let leftIndex = 0;
4+
let rightIndex = 0;
5+
6+
while (rightIndex < n) {
7+
if (nums[rightIndex] === 0) {
8+
k--;
9+
}
10+
11+
if (k < 0) {
12+
k += 1 - nums[leftIndex]!;
13+
leftIndex++;
14+
}
15+
16+
rightIndex++;
17+
}
18+
19+
return rightIndex - leftIndex;
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { longestOnes } from '@/arrays-and-strings/max-consecutive-ones-iii.js';
2+
3+
describe('Arrays and Strings: Max Consecutive Ones III', () => {
4+
test.each([
5+
{ nums: [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k: 2, output: 6 },
6+
{
7+
nums: [0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1],
8+
k: 3,
9+
output: 10,
10+
},
11+
{ nums: [0, 1, 1], k: 0, output: 2 },
12+
])('longestOnes($nums, $k) === $output', ({ nums, k, output }) => {
13+
expect(longestOnes(nums, k)).toStrictEqual(output);
14+
});
15+
});

0 commit comments

Comments
 (0)