mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 08:16:50 +08:00
feat: add maxConsecutiveOnes implementation (#1285)
This commit is contained in:
30
Dynamic-Programming/Sliding-Window/MaxConsecutiveOnes.js
Normal file
30
Dynamic-Programming/Sliding-Window/MaxConsecutiveOnes.js
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
/**
|
||||||
|
* @function maxConsecutiveOnes
|
||||||
|
* @description Given a binary array nums, return the maximum number of consecutive 1's in the array.
|
||||||
|
* @param {number[]} nums
|
||||||
|
* @return {number}
|
||||||
|
* @see [Leetcode link](https://leetcode.com/problems/max-consecutive-ones/)
|
||||||
|
*/
|
||||||
|
export const maxConsecutiveOnes = (nums) => {
|
||||||
|
if (!nums.length) return 0
|
||||||
|
|
||||||
|
let result = 0
|
||||||
|
let k = 0
|
||||||
|
|
||||||
|
for (
|
||||||
|
let slowPointer = 0, fastPointer = 0;
|
||||||
|
fastPointer < nums.length;
|
||||||
|
fastPointer++
|
||||||
|
) {
|
||||||
|
if (nums[fastPointer] === 0) k--
|
||||||
|
|
||||||
|
while (k < 0) {
|
||||||
|
if (nums[slowPointer] === 0) {
|
||||||
|
k++
|
||||||
|
}
|
||||||
|
slowPointer++
|
||||||
|
}
|
||||||
|
result = Math.max(result, fastPointer - slowPointer + 1)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
import { maxConsecutiveOnes } from '../MaxConsecutiveOnes.js'
|
||||||
|
|
||||||
|
describe('maxConsecutiveOnes', () => {
|
||||||
|
it('expects to return 0 when argument is empty array', () => {
|
||||||
|
expect(maxConsecutiveOnes([])).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('expects to return 3', () => {
|
||||||
|
expect(maxConsecutiveOnes([1, 1, 0, 1, 1, 1])).toBe(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('expects to return 2', () => {
|
||||||
|
expect(maxConsecutiveOnes([1, 0, 1, 1, 0, 1])).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('expects to return 5', () => {
|
||||||
|
expect(maxConsecutiveOnes([0, 1, 1, 1, 1, 1, 0, 0, 1, 0])).toBe(5)
|
||||||
|
})
|
||||||
|
})
|
Reference in New Issue
Block a user