Max Consecutive Ones III LeetCode solution in JavaScript

1
/*
2
* @param {number[]} nums
3
* @param {number} k
4
* @return {number}
5
*/
6
var longestOnes = function (nums, k) {
7
let left = 0;
8
let oneCount = 0;
9
let maxLength = 0;
10

11
for (let right = 0; right < nums.length; right++) {
12
if (nums[right]) {
13
// so if the element is a 1 since 0 is falsy
14
oneCount++;
15
}
16

17
if (right - left + 1 - oneCount > k) {
18
// check if we've used all of our replacements
19
if (nums[left]) {
20
// start shrinking the window if its a 1 we subtract a count from oneCount
21
oneCount--;
22
}
23
left++;
24
}
25

26
maxLength = Math.max(maxLength, right - left + 1); // update maxLength each iteration for largest window
27
}
28

29
return maxLength;
30
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0