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.