Skip to content

Commit 5ce828b

Browse files
authored
feat: add maxConsecutiveOnes implementation (TheAlgorithms#1285)
1 parent 55c18ae commit 5ce828b

File tree

2 files changed

+49
-0
lines changed

2 files changed

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

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy