From 46f0eb339f98eaacc0a97a40850c65ae1656bc14 Mon Sep 17 00:00:00 2001 From: HereBeAndre Date: Fri, 10 Feb 2023 19:44:09 +0100 Subject: [PATCH] feat: add maxConsecutiveOnesIII implementation --- .../Sliding-Window/MaxConsecutiveOnesIII.js | 32 +++++++++++++++++++ .../test/MaxConsecutiveOnesIII.test.js | 15 +++++++++ 2 files changed, 47 insertions(+) create mode 100644 Dynamic-Programming/Sliding-Window/MaxConsecutiveOnesIII.js create mode 100644 Dynamic-Programming/Sliding-Window/test/MaxConsecutiveOnesIII.test.js diff --git a/Dynamic-Programming/Sliding-Window/MaxConsecutiveOnesIII.js b/Dynamic-Programming/Sliding-Window/MaxConsecutiveOnesIII.js new file mode 100644 index 0000000000..f4366453ec --- /dev/null +++ b/Dynamic-Programming/Sliding-Window/MaxConsecutiveOnesIII.js @@ -0,0 +1,32 @@ +/** + * @function maxConsecutiveOnesIII + * @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. + * @param {number[]} nums + * @param {number} k + * @return {number} + * @see [Leetcode link](https://leetcode.com/problems/max-consecutive-ones-iii/) + */ +export const maxConsecutiveOnesIII = (nums, k) => { + if (!nums.length) return 0 + + let result = 0 + + for ( + let slowPointer = 0, fastPointer = 0; + fastPointer < nums.length; + fastPointer++ + ) { + if (nums[fastPointer] === 0) { + k-- + } + + while (k < 0) { + if (slowPointer === 0) { + k++ + } + slowPointer++ + } + result = Math.max(result, fastPointer - slowPointer + 1) + } + return result +} diff --git a/Dynamic-Programming/Sliding-Window/test/MaxConsecutiveOnesIII.test.js b/Dynamic-Programming/Sliding-Window/test/MaxConsecutiveOnesIII.test.js new file mode 100644 index 0000000000..5ea7df0ba3 --- /dev/null +++ b/Dynamic-Programming/Sliding-Window/test/MaxConsecutiveOnesIII.test.js @@ -0,0 +1,15 @@ +import { maxConsecutiveOnesIII } from '../MaxConsecutiveOnesIII' + +describe('maxConsecutiveOnesIIIIII', () => { + it('expects to return 0 when argument is empty array', () => { + expect(maxConsecutiveOnesIII([], 3)).toBe(0) + }) + + it('expects to return 6', () => { + expect(maxConsecutiveOnesIII([1, 1, 0, 1, 1, 1], 1)).toBe(6) + }) + + it('expects to return 8', () => { + expect(maxConsecutiveOnesIII([1, 0, 1, 1, 1, 1, 0, 1], 2)).toBe(8) + }) +})