Max Consecutive Ones III
LeetCode 1004 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Longest window with ≤ k zeros.
আমি Max Consecutive Ones III (LeetCode 1004) এভাবে সমাধান করেছি — Variable Window – Longest প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Flipping at most k zeros means: find the longest window containing at most k zeros. Grow the window to the right; when it holds too many zeros, slide the left edge.
Approach
- 1
Count zeros in the window.
- 2
If zeros > k, move l right (decrement if a zero leaves).
- 3
Track the window length.
আমি কীভাবে সমাধান করেছি
Sliding windowPythonO(n) time · O(1) space
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
#sliding window and two pointer
#count the number of zeroes in the current window
#if it exceeds, shrink from left, take care of count of 0 - left most position
l=0
r=0
cnt_zeros = 0
max_length = float("-inf")
while r<len(nums):
cur = nums[r]
if cur==0:
cnt_zeros+=1
if cnt_zeros>k:
if nums[l]==0:
cnt_zeros-=1
l+=1
max_length=max(max_length,r-l+1)
r+=1
return max_length
Max Consecutive Ones III — সাধারণ প্রশ্ন
Max Consecutive Ones III-এর পেছনে intuition কী?
Flipping at most k zeros means: find the longest window containing at most k zeros. Grow the window to the right; when it holds too many zeros, slide the left edge.
Max Consecutive Ones III (LeetCode 1004) কীভাবে সমাধান করবেন?
1. Count zeros in the window. 2. If zeros > k, move l right (decrement if a zero leaves). 3. Track the window length.
Max Consecutive Ones III-এর time আর space complexity কত?
Time: O(n)। Space: O(1)। (Accepted approach: Sliding window।)
Max Consecutive Ones III-এ সাধারণ ভুলগুলো কী?
The window never shrinks, only slides — that's fine because we only need the max length.