# 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

1/**2 * @param {number[]} nums3 * @param {number} k4 * @return {number}5 */6var longestOnes = function (nums, k) {7 let [res, numberOfZeros, left] = [0, 0, 0]89 for (let right = 0; right < nums.length; right++) {10 if (nums[right] === 0) {11 numberOfZeros++12 }1314 if (numberOfZeros > k) {15 while (numberOfZeros > k) {16 if (nums[left] === 0) {17 numberOfZeros--18 }19 left++20 }21 }2223 // think when left = 0, right = 0, the length should be 124 res = Math.max(res, right - left + 1)25 }2627 return res28}

## Comments

Loading comments...

## Tags

leetcode

array

sliding window

## Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

**Fact corner:** Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

**Still hesitate?** Read HoningJS author's guide on dealing with Toptal interview process.

## 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