LeetCode Max Consecutive Ones III Solution Explained - Java

preview_player
Показать описание


Preparing For Your Coding Interviews? Use These Resources
————————————————————

Other Social Media
----------------------------------------------

Show Support
------------------------------------------------------------------------------

#coding #programming #softwareengineering
Рекомендации по теме
Комментарии
Автор

what helped me understand this is the realization that i and j are not the actual edges of the longest consecutive segment.
the window never shrinks, so the max length is kept track of implicitly by the window's size.

artur
Автор

took a while but i get it now, however I think its more intuitive to just cache the maxLen in a variable and shrink until K is positive again rather than caching the width throughout.

danielpark
Автор

Can anyone please explain why i-j always gives the correct result without keeping track of the max subarray at all times.

tapanbasak
Автор

for people who are looking for python3 solution:
l = 0
for r in range(len(nums)):
if nums[r] == 0:
k -= 1
if k < 0:
if nums[l] == 0 :
k += 1
l += 1
r += 1
return r - l

mehdihassan
Автор

Key thing to be explained is how the pointers are to be updated which was not explained clearly. He also got confused when coding and somehow it worked.

vijayakumareyunni
Автор

public class Solution {
public int LongestOnes(int[] nums, int k) {
int left=0;
int right=0;
int ck = k;
int maxNu = 0;
while(right<nums.Length){
int cn = nums[right];
if(cn==1)
right++;
else if(cn==0)
{
if(ck>0)
{
ck--;
right++;
}else{
if(nums[left]==0)
{
ck++;
left++;
}else
left++;
}
}
maxNu = Math.Max(maxNu, right-left);
}
return maxNu;
}
}

mohammedghabyen
Автор

that was really simple, great explanation

subhamshaw
Автор

while the code is simple, you dont get the longest number of ones, which is not the right answer.

emerylin
Автор

This is much easier to understand than the most upvoted in discussion, Thanks Nick!!

miaohong
Автор

Straight forward Explanation. Thanks Nick

SnehaBharathiReddy
Автор

2 mins and 30 seconds into the video, and Nick's like enough talk, let's just get straight to business😂😂 respect man👍

akshittyagi
Автор

What about the test case and with K as 2?
In that case- j wouldn't be able to reach a 0.
How would we get the answer in that case??

edwardnewgate
Автор

What happens if i reaches end before k becomes positive?

sujayshanbhag
Автор

this guy doesnt understand the solution...it can be seen from his explanation. but one thing is sure, he memorized it well for this presentation :D

ladro_magro
Автор

What would be this test case "1110" if k = 1 the output will be 3 right, but the above code returning 4, can anyone please suggest me?

comedycentral
Автор

Oh! This guy is GOLD!!! Thankyou so much!

BharatiSubramanian