Skip to content

Commit 55c18ae

Browse files
authored
feat: add maxConsecutiveOnesIII implementation (TheAlgorithms#1286)
1 parent 49bd1fd commit 55c18ae

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @function maxConsecutiveOnesIII
3+
* @description Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.
4+
* @param {number[]} nums
5+
* @param {number} k
6+
* @return {number}
7+
* @see [Leetcode link](https://leetcode.com/problems/max-consecutive-ones-iii/)
8+
*/
9+
export const maxConsecutiveOnesIII = (nums, k) => {
10+
if (!nums.length) return 0
11+
12+
let result = 0
13+
14+
for (
15+
let slowPointer = 0, fastPointer = 0;
16+
fastPointer < nums.length;
17+
fastPointer++
18+
) {
19+
if (nums[fastPointer] === 0) {
20+
k--
21+
}
22+
23+
while (k < 0) {
24+
if (slowPointer === 0) {
25+
k++
26+
}
27+
slowPointer++
28+
}
29+
result = Math.max(result, fastPointer - slowPointer + 1)
30+
}
31+
return result
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { maxConsecutiveOnesIII } from '../MaxConsecutiveOnesIII'
2+
3+
describe('maxConsecutiveOnesIIIIII', () => {
4+
it('expects to return 0 when argument is empty array', () => {
5+
expect(maxConsecutiveOnesIII([], 3)).toBe(0)
6+
})
7+
8+
it('expects to return 6', () => {
9+
expect(maxConsecutiveOnesIII([1, 1, 0, 1, 1, 1], 1)).toBe(6)
10+
})
11+
12+
it('expects to return 8', () => {
13+
expect(maxConsecutiveOnesIII([1, 0, 1, 1, 1, 1, 0, 1], 2)).toBe(8)
14+
})
15+
})

0 commit comments

Comments
 (0)