Max Consecutive Ones III LeetCode solution in JavaScript
1/*2* @param {number[]} nums3* @param {number} k4* @return {number}5*/6var longestOnes = function (nums, k) {7let left = 0;8let oneCount = 0;9let maxLength = 0;1011for (let right = 0; right < nums.length; right++) {12if (nums[right]) {13// so if the element is a 1 since 0 is falsy14oneCount++;15}1617if (right - left + 1 - oneCount > k) {18// check if we've used all of our replacements19if (nums[left]) {20// start shrinking the window if its a 1 we subtract a count from oneCount21oneCount--;22}23left++;24}2526maxLength = Math.max(maxLength, right - left + 1); // update maxLength each iteration for largest window27}2829return maxLength;30};