# LeetCode: Max Consecutive Ones III Solution

Find the longest contiguos subsequences with K zeros at most

## Approach

Maintain a window of k zeros at most

Calculate max whenever on every window's size changed

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} nums3 * @param {number} k4 * @return {number}5 */6var longestOnes = function (nums, k) {7  let [res, numberOfZeros, left] = [0, 0, 0]8
9  for (let right = 0; right < nums.length; right++) {10    if (nums[right] === 0) {11      numberOfZeros++12    }13
14    if (numberOfZeros > k) {15      while (numberOfZeros > k) {16        if (nums[left] === 0) {17          numberOfZeros--18        }19        left++20      }21    }22
23    // think when left = 0, right = 0, the length should be 124    res = Math.max(res, right - left + 1)25  }26
27  return res28}```

leetcode

array

sliding window

## Next Post

Toptal Interview Process Guide and Review

Jul 2, 2021

Journey of a non-native English-speaker developer on looking for a remote opportunity

## Previous Post

LeetCode: Remove All Adjacent Duplicates In String

Jun 29, 2021

Remove all adjacent and equal letters

Search Posts