forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add maxConsecutiveOnesIII implementation (TheAlgorithms#1286)
- Loading branch information
1 parent
49bd1fd
commit 55c18ae
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
32 changes: 32 additions & 0 deletions
32
Dynamic-Programming/Sliding-Window/MaxConsecutiveOnesIII.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
} |
15 changes: 15 additions & 0 deletions
15
Dynamic-Programming/Sliding-Window/test/MaxConsecutiveOnesIII.test.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
}) | ||
}) |