From efcb9932d16a23149808eb55ccd048311ea149f0 Mon Sep 17 00:00:00 2001 From: HereBeAndre Date: Thu, 9 Feb 2023 23:52:56 +0100 Subject: [PATCH] feat: add maxConsecutiveOnes implementation --- .../Sliding-Window/MaxConsecutiveOnes.js | 30 +++++++++++++++++++ .../test/MaxConsecutiveOnes.test.js | 19 ++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 Dynamic-Programming/Sliding-Window/MaxConsecutiveOnes.js create mode 100644 Dynamic-Programming/Sliding-Window/test/MaxConsecutiveOnes.test.js diff --git a/Dynamic-Programming/Sliding-Window/MaxConsecutiveOnes.js b/Dynamic-Programming/Sliding-Window/MaxConsecutiveOnes.js new file mode 100644 index 0000000000..9e248b338c --- /dev/null +++ b/Dynamic-Programming/Sliding-Window/MaxConsecutiveOnes.js @@ -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 +} diff --git a/Dynamic-Programming/Sliding-Window/test/MaxConsecutiveOnes.test.js b/Dynamic-Programming/Sliding-Window/test/MaxConsecutiveOnes.test.js new file mode 100644 index 0000000000..38e4917251 --- /dev/null +++ b/Dynamic-Programming/Sliding-Window/test/MaxConsecutiveOnes.test.js @@ -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) + }) +}) 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