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[]} nums
3 * @param {number} k
4 * @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 1
24 res = Math.max(res, right - left + 1)
25 }
26
27 return res
28}

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

Previous Post

LeetCode: Remove All Adjacent Duplicates In String

Jun 29, 2021

Remove all adjacent and equal letters

HoningJS

Search Posts