Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 1004 · Variable Window – Longest

Max Consecutive Ones III

LeetCode 1004 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Longest window with ≤ k zeros.

మధ్యస్థంArrayBinary SearchSliding WindowPrefix Sum
LeetCode లో తెరవండి ↗

నేను 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. 1

    Count zeros in the window.

  2. 2

    If zeros > k, move l right (decrement if a zero leaves).

  3. 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.